- Home /
array index is out of range (C#)
Hi guys! I'm new to the forum as well as Unity, but haven't managed to find an answer after a couple of hours.
I've been working on trying to get a texture2d array to run through som images once I push a GUI.Button. So far I've managed to get it to run through the seqence once before I get the message " array index is out of range".
My code: using UnityEngine; using System.Collections;
public class AnimationCode : MonoBehaviour {
public GUIStyle style;
public Texture2D[] FlipFrames = new Texture2D[5];
int timer = 0;
int change = 0;
int test = -1;
bool buttonClicked = false;
public void Start() {
}
void OnGUI() {
if (GUI.Button(new Rect(0, 0, Screen.width, (Screen.height - (Screen.width/6))), FlipFrames[change], style)) {
test = 0;
}
}
// Update is called once per frame
void Update () {
if (test < 6) {
if (test > -1) {
change++;
}
else {
change = 0;
test = -1;
}
}
}
}
It seems as though the problem comes after the seqence has played through and the "change" int won't revert in the update method. Meaning I can't seem to stop the loop for some reason. Also, I can't seem to access the FlipFrames length parameter at all.
Can anyone explain to me what it is that I'm doing wrong?
Answer by robertbu · Feb 05, 2014 at 03:56 PM
I assume you want the sequence to run through once and then stop. Your logic is a bit convoluted here for that behavior. I believe you can fix your code by changing line 24 to:
if (change < 6) {
right now, after test get set to 0, change is incremented forever and therefore goes out of bounds of the array.
Please accept the answer if it solved your problem. If you don't know how to do this, watch the tutorial video on the right and read the FAQ.
Answer by zee_ola05 · Feb 05, 2014 at 04:00 PM
If you want to loop through your array, you can use the modulo operator to make sure you won't get out of bounds.
change = (change + 1) % FlipFrames.Length; // sequence: 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4...