Destroy Your Enemies — Make Them Explode!

In some of my previous articles, I have demonstrated creating 2D animations inside of Unity for various effects. Today, I will expand upon that concept and use it to create a death animation for the enemy ships!

Creating the animation itself is simple: place all the desired frames in the Animation window and save the new animation.

For more information on how to use this system, check out my previous articles!

Now, this animation doesn’t just play at all times, so we need to set up a trigger system to ensure it only occurs when the enemy dies (which is when it collides with a laser or our player ship).

Opening up Unity’s Animator window, we can look at the animation states for the enemy ship.

Window>Animation>Animator

By default, the animation created will be the default anim, meaning it will play right away. To stop this, we create a new empty animation, then make a transition to our “on death” animation and give it parameters.

Under the parameters tab we can create a new parameter of type trigger, then access it through code.

The trigger parameter “Death” will be used to start the animation.

NOTE: Make sure the transition between “Empty” and your animation DOES NOT HAVE EXIT TIME CHECKED.

Now inside of the enemy C# script we can begin the logic. First, we need a handle to the animator, which we can set as a variable and then use GetComponent to access.

New variable for the animator.
Added line 17 to store the animator.

Finally, we can access information on the animator just like we can call functions from other scripts!

Inside of OnTriggerEnter2D, we add this to our enemy death code.

Let’s see it in action!

Enemies explode on death!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store