- Home /
Choosing random number of different gameobjects
Hello, this question was probably asked before but I can't seem to get my script working properly in my game. I have 10 of the same gameobject in the scene with the same names & same tag just different transforms. I wanted to get a random number of different game objects to just move towards a position but either 1 or all of them moves when changing things with the script.
public Transform center;
public GameObject[] Obj;
int index;
public float speed, dist;
void Start()
{
index = Random.Range(0, Obj.Length);
}
void Update()
{
for (var i = 0; i < 10; i++)
{
if (Vector3.Distance(center.position, Obj[index].transform.position) <= dist)
{
Obj[index].transform.position = Vector2.MoveTowards(Obj[index].transform.position, center.position, -1 * speed * Time.deltaTime);
}
}
}
I tried your script and it is working fine at my side, i'm just facing direction problem but clearly that's not your issue. I don't know why but i am not able to upload screenshot. But it doesn't see that the bug you are asking about is present in the script.
Answer by Artik2442 · Jun 22, 2020 at 02:36 PM
Is it because you are using a "for" loop into the Update method? Because at each frame, the "for" loop is called.
Maybe you can do a separate function that takes the "for" loop.
Actual the script doesn't have any issue that person has asked. Script is working fine in my case.
Answer by SofiaFeist · Jun 22, 2020 at 10:09 PM
You're only initializing 'index' once in the Start Method so when you change the position of Obj[index], you're only moving that one specific object in the list. If I understood correctly what you're trying to do, you should have both a random number as the stop condition of the 'for' loop and a random set of indexes for the GameObject array.
Your answer
![](https://koobas.hobune.stream/wayback/20220613001456im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
How do Generate Random Unique int ? 1 Answer
Multiple Cars not working 1 Answer
using Switch and Case for 50% chance of occurance? C# 3 Answers
Teleporting camera and gameobjekt togather at random? 0 Answers