Making the enemies go Boom!

Poof!

Enemies that just disappear in an instant aren’t really that satisfying.

Boom!

Adding an explosion animation makes it have much more impact.

Achieving that isn’t too difficult, as we’ve already been through making an animation. The only thing different this time is that we need to have it only play when we want it to!

There are a few different types of parameter types to choose from:
Floats, Ints, Bools, and Triggers.
Floats and ints are number values and would be useful for making the correct animation play based on which direction the object is moving.
Since all I need is to “signal” that the enemy has been destroyed, and it will never be “un-destroyed”, the trigger is better suited than the bool here.

The next step is to have the script signal to the animator controller when the enemy has been shot.

I created a method OnEnemyDeath() to control what should happen when the enemy is shot or crashed into.

  • Null-Checking for the animator component, which I’ve cached to the _anim variable in Start(). If that is present and accounted for, use the SetTrigger method to “activate” the explosion animation.
  • The _dead bool is used to prevent the enemy gameobject from moving when it is destroyed. Making the explosion stay in place.
  • I then proceed to destroy the Collider component, to prevent the explosion from blocking any subsequent shots, or from damaging the player should he come too close.
  • Finally, the gameobject is destroyed, but with a delay to allow the animation to play through.
    Without the delay, all of the above code would be for nothing, as it would destroy the gameobject, and at the same time the explosion that very frame 😅

Thanks for reading!