Index is less than 0 or more than or equal to the list count

Well i have this code:

var ListaCubos : GameObject[];// cria uma lista para mostrar qual cubo se refere a qual número.

var NumeroIteracoes : int; //é usado para saber o número de vezes que será gerará números aleatórios

var ListaRepetida : int; // lista para mostrar os numeros de 0 a 9

var Vetor = new Array ();// vetor para armazenar os números

function Start ()
{
for(var j : int = 0; j < NumeroIteracoes; j++)
{
Vetor[j]=0;
}

for(var i : int = 0; i < NumeroIteracoes; i++) 
{
	var a: int=Random.Range(0,10);
		
	Vetor[a] = Vetor[a]+1;
		

	ListaRepetida[a] += 1; // mostra no editor quantas vezes cada numero (0 a 9) apareceu 
	
	ListaCubos[a].transform.localScale.y += 10; //muda a escala do cubo referente ao numero em 20
	ListaCubos[a].transform.localPosition.y += 5; //sobe a posiçao na metade da quantidade que escalou
	
}

}

and Unity gave me it:

ArgumentOutOfRangeException: Index is less than 0 or more than or equal to the list count.
Parameter name: index
8
System.Collections.ArrayList.ThrowNewArgumentOutOfRangeException (System.String name, System.Object actual, System.String message)
System.Collections.ArrayList.get_Item (Int32 index)
UnityScript.Lang.Array.get_Item (Int32 index)
ContarRandom.Start () (at Assets/Scripts/ContarRandom.js:14)

I don’t understand why

Pretty sure I answered this question yesterday for you. http://answers.unity3d.com/questions/161461/array-index-is-out-of-range.html

1 Answer

1

Try this, it should fix your problem. Just call the length of the array so no matter what length your array is, this will always be correct and you won’t get this issue.

   for(var i : int = 0; i < ListaRepetida.length; i++)

That way no matter how much you shrink or grow this array, the FOR will always be accurate. No need for this variable. One less variable, better result.

   var NumeroIteracoes : int;  // No Need for this

Hope that helps. Accept this answer if it works for you. :wink: