Creating Enemy Explosions
Well, now that we have a functioning End Game and are able to Reload the current scene, how about we add an explosion to our enemy when it is destroyed?
As previously mentioned, I received a number of sprites with this course; 2D Game Development from GameDevHQ; quite a few of these I will use for the enemy explosion.
First thing we will need to do is add an Animation to our Enemy; I am not going to rehash here how to do that, you can follow my guide in Animating Sprites in Unity if necessary.
After adding the Animation to our enemy, if we run the game we will get something similar to:

What the heck is going on? This is not what we wanted to happen, if we left click on our Enemy prefab, then left click on window in the Menu, then left click on Animation followed by left clicking on Animator the following will be displayed:

This Animator component of the Animation shows us that as soon as the enemy is spawned the Animation is played; continuously. As is apparent, this is not what we want.
To make it so this doesn’t happen, we need to right click in the Animator, then left click on Create State and then left click on Empty. We can then rename it to Empty. Once this is done we need to right click on Empty and then left click on Set as Layer Default State, as shown below:

Then we need to right click on Empty and left click on Make Transition and then left click on Enemy_Destroy_anim. If we now run the game, it will run as normal.
How do we now go from the Empty State to the Enemy_Destroy_anim State? This of coarse, needs to be done with code.
However, before we can start to code we need to set a Trigger condition in our Animator. This is done by left clicking on Parameters, left clicking on the plus sign, left clicking on Trigger and renaming the Trigger to OnEnemyDeath; in this instance. Then we need to left click on the Transition line, then under conditions left click the plus sign and then left click the newly created condition OnEnemyDeath. As shown below:

Now, in order for us to use this Animation we will need to introduce another variable into our Enemy script; such as:

Then in our Start method we will need to cache a reference to this variable using:

Now, in order to Trigger this Animation, we need to add:

To both the if(other.tag is “Player”) and else if (other.tag is “Laser”) parts of the code in the OnTriggerEnter method of our Enemy script.
Saving the script, and jumping back into Unity and running the game will give:

As can be seen, there is quite a delay between when the laser hits the enemy and the Animation is played. This is because when a Transition is created it has default settings as below. Making everything zero, and un-checking Has Exit Time and Fixed Duration will remedy this.
