What does IndexOutOfRangeException: Array index is out of range mean?

I am doing a Unity tutorial and have run into an error. OutofRangeException : Array index is out of range. What does this mean and how do i fix it? Here is my code :

#pragma strict
//Enemy Script

//Inspector Variables
var shapeColor : Color[];
var numberOfClicks : int = 2;
var respawnWaitTime : float = 2.0;
//Private Variables


//Update is called every frame
function Update () 
{
     if (numberOfClicks <= 0)
     {
     
	 	var position = Vector3 (Random.Range(-6,6),Random.Range(-4,4),0);//creates random position
	 	RespawnWaitTime();
        transform.position = position;  //moves game object to a new position
        numberOfClicks = 2;     
     }
}
//RespawnWaitTime is used to hide game object for a set amount of time and then unhide it.
function RespawnWaitTime ()
{
  renderer.enabled = false;
  RandomColor();
  yield WaitForSeconds (respawnWaitTime);
  renderer.enabled = true; 
}
//RandomColor used to changematerial of a game object.
function RandomColor ()
{
  var newColor = Random.Range(0, shapeColor.length);
  renderer.material.color = shapeColor[newColor];
}

2 Answers

2

It means you tried to index into an array with an index beyond the end of the array. Looking at this code, the only way I can see it happen is if you failed to initialize shapeColor in the inspector. It is expecting to have at least one valid entry. Go to the inspector, click on the triangle next to ‘ShapeColor’, set a size for the array, and set a color for each entry.

Thank you so much it is working fine now!

If you question is answered, click on the checkmark next to the best answer to close it out. Thanks.

Hi robertbu! :) This answer is really helpful!! I had the same error. I was searching all over my script for almost an hour trying to find out what's wrong. Until I saw this post then tried to look at the inspector for my objects. I found out that what's wrong. I used the incorrect Tag for my objects. Thanks a lot!! I thought I would have scratch my script. :)

shapeColor.lenght-1, will solve it. because if you shapeColor array have 3 colors the maximium index is 2, 0,1,2, now the limit in your code is the array length in my example would be 3.

@Juilancruz - No it won't solve it. Random.Range(int,int) is exclusive of the final value, so it will not produce an out of range value as long as the array has at least one value.