Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity C# - Array index out of range

Tags:

arrays

c#

unity3d

I'm having trouble with unity and here is the code

The error message:

IndexOutOfRangeException: Array index is out of range.
Sequence.fillSequenceArray () (at Assets/Scripts/Sequence.cs:43)
Sequence.Start () (at Assets/Scripts/Sequence.cs:23)

Code:

public int[] colorSequence = new int[100];
public int level = 2;

// Use this for initialization
void Start () {
    anim = GetComponent("Animator") as Animator;
    fillSequenceArray ();
    showArray (); // just to know

}

// Update is called once per frame
void Update () {

}

public void showArray(){
    for (int i = 0; i < colorSequence.Length; i++) {
        Debug.Log ("Position " + i + ":" + colorSequence[i]);
            }
}

 public void fillSequenceArray(){
    for (int i = 0; i < level; i++) {
        int numRandom = Random.Range (0, 3);    

        if (colorSequence[i] == 0) {
            colorSequence[i] = numRandom;
        }
    }
}

I have tried to change the last if to if (!colorSequence[i].Equals(null)), or if (colorSequence[i] == null) and the same error occurs. Even if I delete this if, the error occurs when I try to fill colorSequence[i] = numRandom;

like image 754
dinizknight Avatar asked Oct 20 '22 21:10

dinizknight


1 Answers

You have to check whether the the array contains a value at that index before attempting to access it. Doing otherwise will throw an error instead of returning null.

You can easily check it using the array's length property:

    if (colorSequence.Length > i) {
        colorSequence[i] = numRandom;
    }
like image 184
Jan Berktold Avatar answered Nov 04 '22 21:11

Jan Berktold