Unity C# - 数组索引超出范围

时间:2014-11-25 18:41:16

标签: c# arrays unity3d

我遇到了团结问题,这是代码

错误消息:

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

代码:

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

我尝试将上一个if更改为if (!colorSequence[i].Equals(null)),或者 if (colorSequence[i] == null)并发生同样的错误。即使我删除了这个if,当我尝试填充colorSequence[i] = numRandom;

时也会发生错误

2 个答案:

答案 0 :(得分:2)

在尝试访问该数组之前,您必须检查该数组是否包含该索引处的值。否则将抛出错误而不是返回null。

您可以使用数组的长度属性轻松检查它:

    if (colorSequence.Length > i) {
        colorSequence[i] = numRandom;
    }

答案 1 :(得分:0)

与许多语言不同,C#不会自动填充数组&#34; slot&#34;当您尝试访问它时,在null范围之外。首次声明数组时,必须明确说明其长度,并且在这些边界之外读取或写入的任何尝试都将产生错误。

var colorSequence = new int[length];

如果您想要一个可以在添加或删除项目时动态增长或缩小的列表,您可能需要List<T>