Death Animations In Unity 2D
Death can be tricky in game development, more so than you might at first expect. The problem essentially, is that when something dies it has to be cleaned up. This means destroying an entity or game object, but before that we typically have to change it’s state. It wouldn’t make sense in most cases for something to immediately poof out of existence when it dies, so we typically have to do some kind of change of state first, and schedule the thing that died for removal later.
There are a couple of tricks to getting this to work right in Unity, at least as far as 2D games go. In this case we’re going to display our death by displaying some kind of animation. Whether it’s a particle on top of our existing sprite, or an animation baked into the sprite itself, we’re still playing an animation clip, which in Unity is hooked up through the Animator.
Here we have to set up a transition with a condition to be triggered through code when our game object dies. Notably, the New State idle animation unity creates by default has a cycle time on exit, so we have to cut that short when we play a death animation, otherwise our animation won’t play exactly when we want it to.
Once this is all set up, all we have to do is add our animation trigger when our game object dies. Note that if there are other things you want to stop doing, you’re going to need a dead state on your game object as well, to make it stop behaving as if it were alive. In my use case, I wanted to blow up my enemy, meaning I get to remove the game object for them as soon as their animation clip is done.
This leaves us with a game object that plays an explosion animation as soon as it is told to die, and then waits to clean itself up until after that animation finishes. You could also wait longer if you wanted to leave a dead enemy lying around, or do any number of other things such as even provide ways for them to come back to life.
The possibilities in Unity are really unlimited, unlike some more focused game engines that let you do things more easily, but limit their functionality by hard coding things like what it means for something to die. In Unity you do have more work to do to even create the concept of death within your game, but as you can see here it isn’t that much work after all, and with a little practice there is a lot that you can do.