Here Comes the BOOM! Visual Effects in Unity
So far, the enemies in this space shooter game have been just vanishing instantly when we hit them with the laser gun. That’s really boring! People these days want excitement and explosions, like this one:
We can easily set this up for the enemy prefabs up just the same as we did for the powerups. (See this article for more details)
Now we run the game and get complete pandemonium.
The reason this havoc is unfolding is because the explosion animation is automatically playing and looping for every enemy on the screen. Ideally, we want this animation only to play when they destroyed by a laser or by running into the player.
Turning off the loop is easy. When we select the animation clip, there’s a checkbox in the inspector so we can turn looping on or off.
Timing the animation correctly is a bit more difficult. We are going to use Unity’s Animator window to help get that done. First we can right-click to create a new animation state that will stay empty. This will be the default, un-exploded behavior of the enemies. We set it to the default state so that the enemies play this empty animation instead of immediately exploding.
Now we can right-click this new state and create a transition to the Enemy_Destroyed animation. We can use this to play the explosion animation when it is the right time.
To time this properly we require a trigger that we can access in the Enemy script. We can create one by clicking Parameters and the + button.
To utilize this trigger, we select the transition from the empty state to the Enemy_Destroyed state, and add a new condition in the inspector. When this condition is met, it will automatically switch states to Enemy_Destroyed, thus playing the animation and causing that big explosion.
We want that explosion to play right away, so we can uncheck the “Has Exit Time” box for that transition as well.
Now we just need to activate that trigger in the Enemy script. We’ll need a variable to access the Animator component.
Because enemies can be destroyed in multiple ways, it’s a good idea to make a new helper method to avoid having to copy code in multiple places. Here is the new EnemyDeath method that stops their movement and collision, activates the animation trigger, and destroys the enemy after a few seconds.
Now we just call this new method when the enemy collides with something.
All done! Now it’s time to shoot ’em up and watch the pretty fireworks.