[Solved] Could somebody explain the SpriteIndex -1 to me please?

I know it works but i don’t understand why it works.

In the lecture around 5mins 22secs Ben says that the SpriteIndex starts counting at 0 so we need this to be -1. However wouldn’t this imply that the index would go from Element 0 to a theoretical Element -1. So logically (at least in my head) shouldn’t this be +1 in the script instead?

Also as this Index starts counting at 0 like Ben said, why aren’t the 2 and 3 hit bricks coming into the game with the 1 hit damaged sprite that is in the Element 0 slot?
I know the LoadSprites method isn’t used until collision to change anything so this might be why but its still confusing to me.

Arrays start counting at zero or in other words their index starts at zero. So an array with size = 3 or 3 items in it has:
element 0
element 1
element 2
you acces the first element in the array with an index value of 0

we assign a sprite to each of these array slots or elements.
At start the brick has not been hit yet so timesHit = 0. If i understand your confusion correctly, it’s this line in the LoadSprites() method that is getting you:
int spriteIndex = timesHit -1;
It is setting the index before we load a new sprite so we know which one to load from the sprite array.

This method won’t actually get called until the first time a block gets hit and we enter the OnCollisionEnter2D() method. timesHit gets incremented, so on the first hit it is now equal to 1 (timesHit = 1). If this isn’t a block that gets destroyed after only one hit then we call the LoadSprites() method. Now the spriteIndex gets calculated and since timesHit = 1, the index ends up being zero (spriteIndex = 1 - 1 = 0) and we access the first element in our array, Element 0. spriteIndex will never be equal to -1 and access an element outside of the bounds of the array.

I hope that helps and isn’t too confusing.

1 Like

Hi Josh,

Please accept my apologies for such a late reply, my internet has been very bad for the last few weeks and i have been unable to study.

So in noobish terms as i understand; the Loadsprites method is called upon a hit. The calculation to load the sprite is the “times hit -1” so as we are starting with 1 it loads element 0 which is the first damaged brick sprite.

Thank you so much for your explanation, really appreciate you taking the time to help me out.


Privacy & Terms