- Home /
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.
Answer by Ludiares.du · Sep 11, 2011 at 01:40 PM
Try:
Instantiate(all_the_rocks[Random.Range(0, all_the_rocks.length)], postion, rotation)
Answer by aldonaletto · Sep 11, 2011 at 01:44 PM
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.
Answer by Piflik · Sep 11, 2011 at 03:14 PM
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.
Your answer
Follow this Question
Related Questions
IndexOutOfRangeExeption - Array index is out of range 2 Answers
Out of range error 1 Answer
IndexOutOfRangeException: Array index is out of range 2 Answers
Adding a texture to array textures?! 1 Answer