I'm having trouble with unity and here is the code
The 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 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;
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.
You can easily check it using the array's length property:
if (colorSequence.Length > i) {
colorSequence[i] = numRandom;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With