Creating Enemy Explosions

Objective: Have the enemies play an explosion animation when destroyed.
The first thing to do is to create the explosion animation. We have done this in the past a few times. Here is my article on creating animations in Unity.
There is one difference to this animation. We do not want the animation to play from the start or loop the animation. We need to enter Unity’s Animator view by double-clicking on the animation controller to address this problem.

What we can do in the animator is create a new empty state, and set the new empty state as the default state:

What this does is when the enemy is created, the empty state will play and not the enemy destroyed state. We can then connect the empty state to the destroyed state.

When the Empty state is finished playing, it will then transition to the destroyed state immediately. This happens because there is no condition stopping the transition. In the parameters tab, we can create a trigger called “OnEnemyDeath” and assign it to the transition between the empty and destroyed states.


We should also turn off ‘Has Exit Time’ and the ‘Loop Time’ of the animation to make sure the animation plays immediately when called and only plays once.


Now in code, we need to open up the Enemy script and call the Animator component to access the ‘OnEnemyDeath.’

When the enemy collides with the Player or the Player’s Laser, we will set the animation to play right before the enemy is destroyed.

The 2.8f is there to delay the enemy's destruction until the animation has completed.
The last thing we should do to help prevent bugs in our game is when the enemy is in the destruction animation. The movement speed should be set to 0.
