简体   繁体   中英

Unity C# - Array index out of range

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;

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;
    }

Unlike many languages, C# does not automatically fill an array "slot" outside of its bounds with null when you try to access it. When you first declare the array, you must explicitly state its length, and any attempt to read or write outside those bounds will generate an error.

var colorSequence = new int[length];

If you want a list that can dynamically grow or shrink as you add or remove items, you probably want List<T> instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM