IndexOutOfRangeException help on debug

I’m hitting a IndexOutOfRangeException error on one line of my code and it’s driving me crazy! The code itself works and I know why I’m gave the error but don’t know how to fix (it’s really annoying have the error popup everytime I execute the code).

The part of code is:

public void NextOnMouth()
    {
        if (imageNumber <= mouthImages.Length -1)
        {
            imageNumber++;
            finalImage.sprite = mouthImages[imageNumber];
        }
    }

the error is on the line:

finalImage.sprite = mouthImages[imageNumber];

On the update I call another bit of code that says if imageNumber(int) is bigger than the lenght of the object array, the value of it is 0 and it updates the sprite again.

if (imageNumber >= mouthImages.Length && mouth)
        {
            imageNumber = 0;
            finalImage.sprite = mouthImages[imageNumber];
        }

The error says to me that i’m trying to access the index that is out of the array (but the exact frame its out I reset it to zero, so i try to access a value that I already modified. The code works but I don’t like errors on my console.

Any thoughts?

The last element index in an array is array.length-1. So, when you have

imageNumber = mouthImages.Length - 1;

your code is going to increment its value of 1 and imageNumber value will be out of bounds. Consider to change if condition with

if (imageNumber < mouthImages.Length -1)

or move the increment operator at the end of if statement

Errors never lie.

imageNumber value is out of the mouthImages length.

What I would to is to remove the code in the Update function and having this NextOnMouth function:

public void NextOnMouth()
{
	if(imageNumber >= mouthImages.Length)
	{
		imageNumber = 0;
	} 
	else 
	{
		imageNumber++;
	}
	finalImage.sprite = mouthImages[imageNumber];
}

,I think the reason is that the variable mouth has to be always true so that variable imageNumber can be limited to zero. Otherwise imageNumber will keep growing out of mouthImages length and thus error message appears.

Variable imageNumber could be limited in NextOnMouth() function (after imageNumber++) like this:

imageNumber = Mathf.Clamp (imageNumber, 0, mouthImages.length-1);