Step 14 — Enemies Do An Explode

Now things can get spicy because enemies will go up in a ball of flames when hit.

First add the exploding animation to the Enemy object, same as with the Powerups. But then there’s a problem.

No wait I didn’t even hit you that hard, don’t tell mom

The enemies are playing the explosion as soon as the game starts.

To investigate this we go into the Animator tab.

In order to delay the explosion animation, we have to set create an empty animation state whereby it’s NOT exploding. Right click → Create State → Empty. Then right click on this new state and Set As Layer Default State. Lastly, right click on the new state and Make Transition, drag it to the Enemy_explode_anim. It will now look like this.

Now there’s a tiny delay before the enemies explode, so it’s still not the desired effect. We need a trigger to tell the Animator when to play the explosion.

In the Parameters sub-tab add a Trigger, call it OnEnemyDeath.

Then click on the arrow between the Empty and Enemy_explode_anim, and look in the Inspector. Add the OnEnemyDeath to the Conditions.

This condition will be triggered from the Enemy script, so make the following additions:

Enemy script

Now the explosion will play at the right moment, when the Enemy is destroyed and only then. But wait, there’s another problem.

The Enemy is being destroyed immediately after the SetTrigger is called, so it doesn’t even have time to play. Add a slight delay to the Destroy method of about 2.5 seconds, as that’s about how long the animation lasts.

Destroy(this.gameObject, 2.5f);

So it’s exploding, but still moving, and also it has a delay before exploding. The solutions are:

  • Set speed of the Enemy to zero right after the SetTrigger
  • In the transition arrow between Empty and Enemy_explode_anim, turn off the Has Exit Time checkbox, because otherwise the Empty state is being played to completion before playing the explosion.