- Home /
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?
Answer by j4ke · Feb 05, 2020 at 02:12 PM
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);
This might work better:
public void NextOn$$anonymous$$outh()
{
if(mouth)
{
imageNumber++;
if(imageNumber >= mouthImages.Length)
{
imageNumber = 0;
}
finalImage.sprite = mouthImages[imageNumber];
}
}
Answer by Mym2o · Feb 05, 2020 at 02:19 PM
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
Answer by tormentoarmagedoom · Feb 05, 2020 at 01:28 PM
Errors never lie.
imageNumber value is out of the mouthImages length.
Yes, I said it is, but at the exact time it's out the function on Update calls it back to zero