C# - IndexOutOfRangeException - Array index is out of range

I’m attempting to create some sort of GIF animation script. I’ve sliced an image of 30 frames into 30 different images via the Sprite Editor. Now I’m attempting to loop through them all and changing the background of the GameObject, but it’s giving me an error: Array index is out of range.

This error usually means I’m trying to loop through more sprites than the given size of the array. But I’m not sure if that is happening right here. So, this is my full script:

using UnityEngine;
using System.Collections;

public class AnimatedPauseMenu : MonoBehaviour 
{
    int nFrame;
    public Sprite[] pauseSprites;

	void Start () 
    {
        nFrame = 0;
        pauseSprites = Resources.LoadAll<Sprite>("pausemenu2");
	}
	

	void Update () 
    {
        if (CollisionScript.pPaused == 1 && CollisionScript.pGameOver == 0)
        {
            nFrame++;
            gameObject.GetComponent<SpriteRenderer>().sprite = pauseSprites[nFrame];
            if (nFrame == 30) nFrame = 0;
        }
	}
}

Error line:

gameObject.GetComponent<SpriteRenderer>().sprite = pauseSprites[nFrame];

I’m not entirely sure what is causing this problem. However, I did notice one thing. When I’m attempting to change the array value in the Inspector, it automatically resets to 0 right after I changed the size. So I assume the array has a size of 0, but I’m not able to solve it even when I’m using the following line to define the array:

public Sprite[] pauseSprites = new Sprite[30];

p/s my file names are:
pausemenu2_0 to pausemenu2_29

Thanks for helping!

You are resetting nFrame when it’s 30, your array is 30 long, so the last index is 29 (0 to 29 are the possible indices).

So you will probably want

if (nFrame == 29) nFrame = 0;

You could also check against the length of the array (and substract one from it), so that at a later point you want to re-use this script for another “gif” or want to remove a frame you won’t have to change the script.

put the "if (nFrame == 30) nFrame = 0;" line BEFORE setting sprite. the index is out of range before you reset it…

also, doing GetComponent in Update() is expensive. try the following:

...
public Sprite[] pauseSprites;
private SpriteRenderer _spriteRenderer;
...

then in Start/Awake

_spriteRenderer = gameObject.GetComponent<SpriteRenderer>();

and to use it:

nFrame++;
if (nFrame > pauseSprites.Length)
{
   nFrame = 0;
}
_spriteRenderer.sprite = pauseSprites[nFrame];

it wouldn’t be the worst idea to check that _spriteRenderer is non-null too… little bit of defensive programming rarely hurts :wink:

g.