- Home /
Index out of range for no reason?
Hello, I have a script that randomly chooses an object from 1 to 3 and places the chosen object down. This worked completely fine but even though I didn't seem to change any code it suddenly delivers 10-50 of these errors each time I press play. The even stranger thing is that the errors don't seem to do anything, do I even need to bother with them? Code:
public GameObject[] objects;
void Start()
{
int rand = Random.Range(0, objects.Length);
Instantiate(objects[rand], transform.position,Quaternion.identity);
}
Thanks for taking the time to read my post, any help will be appreciated!
Have you filled the objects
array in the inspector?
The only reason you have this error is that the array is empty.
Thanks for replying, and yes I do have it filled in, it worked before but now it's suddenly an error. Thanks again.
Can you add a Debug.Log like so and click on the message you will most likely get in the console? The object holding this script will get highlighted.
public GameObject[] objects;
void Start()
{
if(objects.Length == 0)
Debug.LogError("No element in objects array. Click this message", this);
int rand = Random.Range(0, objects.Length);
if(rand >= objects.Length)
Debug.LogError("This message should not appear unless objects is empty " + rand + " >= " + objects.Length, this);
Instantiate(objects[rand], transform.position,Quaternion.identity);
}
Answer by Slepude · Nov 15, 2020 at 06:45 PM
@floppyturtle32 Hmm i don't really know, but make sure you got all the objects in your array placed/instantiated
Your answer
Follow this Question
Related Questions
Random Tile Generation 0 Answers
Unity Projects 01 Stealth - problem! 1 Answer
How to clone randomly 3 Answers
IndexOutOfRangeException: Array index is out of range 2 Answers
Why Do I Suddenly Have This Problem? 0 Answers