Saturday, January 30, 2016

Re-using Unity 2D animations by changing the Sprite at run-time.

In my new game Shuffa brick, I have a number of same sized bricks that I want to animate once and re-use the animation for all colours of the bricks.

I created the animation using a green brick, then in the editor I changed the sprite renderer to use a different coloured sprite.

The change works in the editor, but when running the game it reverted back to the green brick.

In code I tried updating the sprite of the renderer in the Update() of the GameObject but that didn't work either. In the debugger I could see it getting changed but again it went back to the Green brick at run-time.

So in effect what happens is that the animator overwrites whatever sprite we set in code with the one in the animation.

Unite 2014 - 2D Best Practices In Unity

I watched a really good video on YouTube, the important part is where he talks of Sprite animation re-skinning. All I needed from the video was just one word LateUpdate (31mins in). The code in the LateUpdate() is ran after the animator has done it's work. So if we change the renderer's sprite at this moment it stays changed.

Brick animations with LateUpdate()