At the moment my enemies just blink out of existence without a trace. While it could mean that my lasers are overwhelmingly powerful, but as a game feature it’s not that satisfying. To remedy that, I will make my enemies explode once they are destroyed.
The Filebase has sprites for exploding enemies, so all I have to do is to do exactly the same as I’ve done before when adding animations. Except for disabling the Loop Time, the explosion animation doesn’t need to loop.
All is good? As you can see all is definitely not good, because my enemies explode immediately. What causes this? And how to solve it?
For the first question the answer lies in the Enemy_Destroyed Animator Controller. Here as a default Unity attaches the animation directly to the instance where the Enemy GameObject enters the game. To fix this I introduce a new empty state, and rename it to Empty. Then I make that as the default state, and then attach the Empty state to my animation.
Is this enough? No, after all I didn’t set it to ever happen. To make the explosion happen I can add a new trigger type parameter, I call it OnEnemyDeath, then disable, if it already isn’t, and attach it to the transition between the Empty state and the animation.
To have my enemies explode once destroyed, I have to enable this trigger inside my Enemy script. This is fairly easy, all I have to do is to find when the enemy is destroyed. That is when the player or the laser hits the enemy. To access the method SetTrigger, I have to first get a reference to my Animator in the Start method. Remember to check if it’s null, otherwise there will be some error messages.
After that I just call the method SetTrigger, stop the enemy that’s being destroyed. I suppose I could also let it move while being destroyed, have to consider that later on, but for now the enemies stop when hit. And lastly I have to delay the Destroy method, so that the player can see the cool explosion animation.
Except when it’s delayed. To correct this we have to change the settings of the transition between the Empty state and the animation. This forces the animation happen immediately.
And that is how to animate and trigger explosions when something is being destroyed.