Unity Fundamentals — Exploding Enemies

Jose Gil
3 min readApr 20, 2021

--

To improve your game, you will need to create some excitement, and when an enemy is destroyed, it must explode. In this article, we will cover how to add an explosion to your enemy destruction effectively.

What you will need

To create an explosion, you will need a series of sprites to animate the actual event. These sprites will be critical to the explosion being effective. The most effective Animation will start with the GameObject exploding as part of the Animation.

Adding the Explosion Animation

Let’s add an animation to your enemy that will trigger when it is destroyed. Select the enemy GameObject and drag it into the hierarchy. Open the Animation window and create the animation file. Drag the series of sprites for the explosion into the Animation window.

The Animator will create two files. The Animation Clip and the Animator Controller. Select the Animator Clip and deselect the “Loop Time” checkbox so the Animation will not loop.

Open the Animator Window to view the layers of the Animation.

Now the enemy will automatically explode when Instantiated.

Control when the enemy explodes

To control the explosion, we need to add a State to the Animation.

Set the New State to be the Layer Default state.

Add a transition to the Animation.

Now we need to add a trigger to activate the Animation. In the Animator window, add a Trigger and call it OnEnemyDestroyed.

Click on this new transition link and ensure you have deselected the “Has Exit Time” checkbox in the inspector as this will delay the Animation when triggered.

Add this new trigger to the condition of the transition.

Activating the Explosion

Let’s go to the GameObject script and create a variable for the Animation.

private Animator _anim;

In the Void Start method, let’s give this variable its value.

_anim = gameObject.GetComponent<Animator>();

Don’t forget to null check it for error checking.

On any trigger that destroys the enemy, activate the Animation using the following command.

_anim.SetTrigger(“OnEnemyDeath”);

Delay the destruction of the enemy for the duration of the Animation.

Destroy(this.gameObject, 2.3f);

I hope this article has helped you add some bang to your game.

--

--

Jose Gil
Jose Gil

Written by Jose Gil

Unity Developer at Mooski Games

No responses yet