Array index is out of range Error, only when array is used to Instantiate

Hey, i’ve been working on a script that spawns a lot of different rocks; each different rock is a prefab, and they are all placed in an array variable by exposing it to the editor, like so: var all_the_rocks: Transform[];

However when i try to Instantiate an object by using: Instantiate(all_the_rocks[Random.Value * all_the_rocks.length], postion, rotation); the console erratically tells me that the array index is out of range.

As far as i can see, there’s NO WAY the index could be out of range, but at least half the time unity comes to this part of the code it throws up the same error.

Thank you in advance, if i haven’t been clear please tell me and i’ll try to explain myself better.

Try:

Instantiate(all_the_rocks[Random.Range(0, all_the_rocks.length)], postion, rotation)

This will produce out of range index when Random.value returns 1: it will result the index Lenght, but the array has Length-1 elements.

To get random indexes, the best choice is Random.Range:

Instantiate(all_the_rocks[Random.Range(0, all_the_rocks.length)],...);

If the parameters are integers, the int version is used - and it ranges from 0 to max-1.

Try ‘Random.Range(0, all_the_rocks.length)’ instead of ‘Random.Value*all_the_rocks.length’. I guess float values aren’t perfect as an array index.