Unity C # - Array index out of range
I am having unity issues and here is the code
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 tried to change the latter if
to if (!colorSequence[i].Equals(null))
, or
if (colorSequence[i] == null)
and the same error occurs. Even if I remove this one if
, the error occurs when I try to fillcolorSequence[i] = numRandom;
So I am a beginner and this is probably a stupid mistake, but help me please. sorry for any english mistake
source to share
Unlike many languages, C # does not automatically populate an array "slot" outside of its bounds with a help null
when it tries to access it. When you first declare an array, you must explicitly specify its length, and any attempt to read or write outside these bounds will result in an error.
var colorSequence = new int[length];
If you want a list that can grow or shrink dynamically as you add or remove items, you most likely want to List<T>
.
source to share