Creating Enemy Explosions in Unity Part 01
Objective: To create an enemy explosion when they are destroyed!
Next up we are going to create an enemy explosion animation through sprites for when the enemy is destroyed by either getting hit by a laser or by running into the player.
First, let’s start with creating the animation sequence. To do this make sure to have the enemy prefab game object highlighted and then click on the ‘Animation’ tab. Click ‘Create’ and then name it ‘Enemy_Explosion_Anim’. From here, click on the record button and then drag in all the sprites in the sequence. Make sure to press record again when you are happy with the result.
Now by default Unity is going to set this animation to ‘loop’ which we are going to switch off as we only want the sequence to run once when the enemy dies.
We also have an issue where if we hit ‘Play’, the enemy blows up instantly as we haven’t created any logic as to when the enemy explosion should occur.
Unity also automatically attaches an Animator component to the enemy, but we need to enable this by clicking on the tick box. You will also see that the Animator has the enemy controller already attached to it also, so we don’t need to add it. Make sure to save your changes if you are working outside your prefab:
Creating Logic Within the Animator
Let’s now look into using some parameters within the Animator component. We want to create a trigger that is going to switch and play the animation when the enemy dies. So let’s click on the Animator window and under parameters click the + button and we want to add a trigger. We are going to call this trigger ‘OnEnemyDeath’.
Next within the Controller section, let’s right click and click Create State → Empty and then rename this to Empty State. Let’s also make this the Layer Default State and add a transition to the Enemy_Explosion_Anim so we can control the logic.
Then, we are going to press the arrow that leads between Empty State and Enemy_Explosion_Anim and we are going to add the trigger condition that we created:
Now, in the Inspector we are able to add the trigger condition that we created:
Next Up: Let’s look at the scripting side of making this animation trigger!