din*_*ght 5 c# arrays unity-game-engine
我在统一方面遇到麻烦,这是代码
错误信息:
IndexOutOfRangeException: Array index is out of range.
Sequence.fillSequenceArray () (at Assets/Scripts/Sequence.cs:43)
Sequence.Start () (at Assets/Scripts/Sequence.cs:23)
Run Code Online (Sandbox Code Playgroud)
码:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我试图将最后一个更改if为if (!colorSequence[i].Equals(null)),或者
if (colorSequence[i] == null)发生相同的错误。即使删除此内容if,当我尝试填充时也会发生错误colorSequence[i] = numRandom;
在尝试访问数组之前,您必须检查数组是否包含该索引处的值。否则会抛出错误而不是返回 null。
您可以使用数组的 length 属性轻松检查它:
if (colorSequence.Length > i) {
colorSequence[i] = numRandom;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5501 次 |
| 最近记录: |