我在统一方面遇到麻烦,这是代码
错误消息:
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;
时也会发生错误 最佳答案
在尝试访问该数组之前,必须检查该数组是否在该索引处包含一个值。否则将引发错误,而不是返回null。
您可以使用数组的length属性轻松检查它:
if (colorSequence.Length > i) {
colorSequence[i] = numRandom;
}