- Home /
How do you get different random numbers for each object array?
public Transform[] obstacleLocation;
public GameObject[] obstacles;
int obstacleRandomNumber;
void Awake()
{
obstacleRandomNumber = Random.Range (0, obstacles.Length);
SpawnObstacles ();
}
void SpawnObstacles()
{
foreach (Transform obstacleLoc in obstacleLocation) {
Instantiate (obstacles [obstacleRandomNumber], obstacleLoc.position,
obstacleLoc.rotation);
print ("Obstacle");
}
}
The problem is obstacleRandomNumber uses the same number for all the Transforms in the array. How do I do it so that the random number uses a different number for every Transform in the array?
Answer by Yeezyy · Dec 08, 2017 at 11:13 AM
void SpawnObstacles() {
foreach (Transform obstacleLoc in obstacleLocation) {
obstacleRandomNumber = Random.Range (0, obstacles.Length -1);
Instantiate (obstacles [obstacleRandomNumber], obstacleLoc.position,
obstacleLoc.rotation);
print ("Obstacle"); } }
I had to remove the - 1 but other than that, it actually worked perfectly. It makes me feel stupid how I missed this simple solution.
An array of length n size , the last index is n-1 as an array index starts with 0. If obstacleRandomNumber is random as obstacles.Length you will get an array index out of range error
$$anonymous$$e didnt get any errors. when I added the -1 some of the transforms were empty but after removing it all of them were filled with one of the two objects that i wanted