Unity C#-数组索引超出范围 [英] Unity C# - Array index out of range
问题描述
我在统一方面遇到麻烦,这是代码
I'm having trouble with unity and here is the code
错误消息:
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;
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;
推荐答案
在尝试访问该数组之前,必须检查该数组是否包含该索引处的值.否则将引发错误,而不是返回null.
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.
您可以使用数组的length属性轻松地对其进行检查:
You can easily check it using the array's length property:
if (colorSequence.Length > i) {
colorSequence[i] = numRandom;
}
这篇关于Unity C#-数组索引超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!