Array index out of range (when it shouldn’t)

Hello everyone!
I get an array index out of range error when trying to run the following code:

for (int i = UI_HighlightColors.Length; i > 0; i--) {
    Debug.Log("SETTING COLOR TO: UI_HighlightColors[" + i.ToString() + "]" );
    UI_Highlight[UI_ElementNumber].GetComponent<Image>().color = UI_HighlightColors[i];
    yield return new WaitForSeconds(AnimationWaitTime);
}

But really don’t know why. Do you have an idea why?
I tried

UI_Highlight[UI_ElementNumber].GetComponent<Image>().color = UI_HighlightColors[i-1];

instead of the original line and it works without errors then, but I will assign the wrong colors in that case.
Debug.Log will then tell me (which only makes sense) that the first color assigned is the second last of the array. But I want the last one to be assigned first.

Many thanks in advance for any ideas,
Greetings,
Shu

i starts from the arr.Length value, which is by 1 out of range.

Try this:

for (int i = UI_HighlightColors.Length - 1; i >= 0; i--) {
    Debug.Log("SETTING COLOR TO: UI_HighlightColors[" + i.ToString() + "]" );
    UI_Highlight[UI_ElementNumber].GetComponent<Image>().color = UI_HighlightColors[i];
    yield return new WaitForSeconds(AnimationWaitTime);
}
1 Like

Thanks for your quick reply! I just tried it and I have the same problem that I have when using
UI_Highlight[UI_ElementNumber].GetComponent<Image>().color = UI_HighlightColors[i-1];.
The whole thing will start on the second latest of the array and not the latest.

EDIT:
I just noticed: You are right. I have a different problem.
It did in fact start with the latest, but it didn’t go down all the way to the first.
The code that is working:

for (int i = UI_HighlightColors.Length-1; i >= 0; i--) {
    Debug.Log("SETTING COLOR TO: UI_HighlightColors[" + i.ToString() + "]" );
    UI_Highlight[UI_ElementNumber].GetComponent<Image>().color = UI_HighlightColors[i];
    yield return new WaitForSeconds(AnimationWaitTime);
}

I thought the -1 was the only change in your code, so I didn’t change the > to >=.

Thanks again for your help!

I editted my post a few moments ago, what code exactly did you use?

I also edited my last post. It works now perfectly!
This is what I tried first, which didn’t work as intended, because the loop didn’t go through the whole array:

for (int i = UI_HighlightColors.Length-1; i > 0; i--) {
    Debug.Log("SETTING COLOR TO: UI_HighlightColors[" + i.ToString() + "]" );
    UI_Highlight[UI_ElementNumber].GetComponent<Image>().color = UI_HighlightColors[i];
    yield return new WaitForSeconds(AnimationWaitTime);
}