Creating Enemy Explosions

Christian Carter
3 min readJun 4, 2021

--

This tutorial is going to cover making enemies explode when they are destroyed. First, create the enemy explosion animation and attach it to the enemy prefab. If you need a refresher on how to do that you can find one here. Now the animation is running the enemy will explode, all the time. Make sure you uncheck the loop time for the animation.

To fix this you need to modify the controller. Open the enemy animation controller. Right click and create a new empty state. Set the empty state as the default transition. Then add a transition from the empty state to the enemy destroyed animation.

Next, you need to add a parameter for the transition to the destruction animation. Make the parameter a trigger and name it OnEnemyDeath. In the Inspector add a condition, this will automatically come up as the trigger you created since it is the only one. Also, in the Inspector uncheck the “Has Exit Time” box and under Settings set the transition duration to 0. If you don’t do those two steps your animation may take longer than expected to trigger.

The next step is to setup the code to control the trigger. Go to the enemy script. Create a variable for the Animator.

private Animator _anim;

In the start function you want to get access to the Animator, since it is part of the object you do not need to find it but can just assign it to the variable using get component. Make sure to verify that it was assigned.

_anim = this.GetComponent<Animator>();
if (_anim == null)
{
Debug.LogError("The Animator is NULL.");
}

The animation will be called in two different places, when the enemy crashes into the player and when it is hit by a laser. At this point it is a good idea to break out all of the enemy death code into its own function. In the function use the animator SetTrigger function to activate the trigger by passing the name of the trigger to the function. Set the speed of the enemy to 0 so it stops moving. Last add the Destroy function. This time in the destroy function pass a float. This is a delay before the object is destroyed and will allow the animation to be played. To get the exact time for the animation you can go to the anim and look in the animator window to see how long the animation window is. After you create the enemy death function you can use it to replace the Destroy function after the two collision types.

private void EnemyDeath()
{
_anim.SetTrigger("OnEnemyDeath");
_speed = 0;
Destroy(this.gameObject, 2.8f);
}

That is it now the enemy will be destroyed when you shoot it or crash into it!

Good Luck Adventurer!

-Chris

--

--

No responses yet