SpriteRenderer - swapping sprites methods

What Rick has shown here is perfect for this layout of the arkynoid game, but a more robust method would be to use a for loop, and an array/list to cycle through the sprites. I’m using a list here:

[SerializeField] list<SpriteRenderer> hitSprite;

//other bits of code
//the method
int spriteIndex = hitSprite.Count;

for(int a = 0; a < spriteIndex; a++)
GetComponent<SpriteRenderer>().sprite = hitSprite[a];

So something like the above. Also like we’ve been taught, the SerializeField makes selecting objects so much simpler and with arrays and lists you can set the size in the inspector (without doing the code). Gives a good mix between programming and game design.


I get an error:

Assets\Scripts\Block.cs(72,53): error CS0029: Cannot implicitly convert type ‘UnityEngine.SpriteRenderer’ to ‘UnityEngine.Sprite’


Well not sure why that’s happening on your end. Could be something to do with the rest of your code. Mine does work but has a weird bug where it skips to the last sprite every time the hit happens. I mean it’s not perfect but it’s tidier code.

I think skipping to the last sprite is caused by using a for loop like you did. The loop executes multiple times - as long as the condition is true - and “a” is increased every time.
So you are setting the sprite to 0…1…2 and end with the last entry from your list.
But this all happens in this one frame you call the method (or the loop) - not one step every time the method is called.

Yeah I was figuring that was the issue. That’s probably what the solution in this part of the course fixes. I think an easy fix would be to using some conditionals to dictate how the frames go, but that kind of defeats the purpose of this smaller bit of code.

Privacy & Terms