Array index error?
I'm working towards the end of the space shooter tutorial and Unity5 is reporting this error:
IndexOutOfRangeException: Array index is out of range. GameController+c__Iterator2.MoveNext () (at Assets/Scripts/GameController.cs:50)
This is the code I have:
GameObject hazard = hazards [Random.Range (0, hazards.Length)];
How do I fix this?
Answer by Artaani · Mar 16, 2016 at 06:11 PM
This error means that you inserted index larger than length of the array. For example hazards[5] while your hazards array contains only 3 elements.
In your case, it may happens if hazards array is empty, in that case Random.Range (0, hazards.Length) will be 0 but hazards[0] will be out of range
Just use Debug.Log
For example:
Debug.Log ("Length: " + hazards.Length);
int index = Random.Range (0, hazards.Length);
Debug.Log ("index: " + index);
GameObject hazard = hazards [index];
And everything will be clear
Your answer
Follow this Question
Related Questions
,"For" loop looping only once through my array 0 Answers
IndexOutOfRangeException: Array index is out of range. 2 Answers
onClick.AddListener IndexOutOfRangeException error and listener not seen in inspector 0 Answers
C# Index Out of Range Exception When the Index Is Within the Length of the Array 0 Answers