[Solved] Getting Index out of Range


For some reason, I’m getting an array index out of range. I can’t seem to figure out why its doing this. The code is all right but it says its out of range. Using Unity 5.5

Its on line 38 where we are trying to set SpriteRenderer.sprite to the hitSprites at spriteIndex.

1 Like

Can you pop a screenshot up of the LevelManager with the Inspector visible please.

Also - what is the value of spriteIndex when it errors?

If you are not sure, pop a Debug.Log("Index : " + spriteIndex); after you populate it in the LoadSprites() method.

is this what you wanted?

when I debug, the spriteIndex prints out 0.

Also, when my blocks are hit, they are still getting destroyed in 1 hit rather than 2 when I set the max hit at 2 or 3.

1 Like

Hello xxKlearxx,
Just a guess.
You are starting with a “timesHit=0” in Start().

In Function LoadSprites(): “spriteIndex=timesHit-1;”

This may result in a negative number for “spriteIndex” (the array index might be out of range).
Try to “invert” that value.

Hope that helps.


1 Like

but that shouldnt matter. When a brick is hit, timesHit increments and it should be at 1 when it hits that function. That would make spriteIndex = 0 when it gets down to LoadSprites function.

1 Like

Oh. I see.
Shouldnt it be:

if(timesHit >= maxHits){

in OnCollisionEnter2D(…) ?

1 Like

ah yes! thanks! I totally missed that.


Just as a heads up, you can post images directly into the forum, as well as code, it makes it a lot easier for people to see and respond :slight_smile:

Privacy & Terms