With our game progressing nicely, it’s about time to start adding some flare to it. Shooting enemies is all well and good but they certainly shouldn’t just blink out of existence!
For this, similarly to our powerup animations, you will need some sprites for your explosion animation. Filebase is an incredible resource for such game assets!
Drag your first explosion sprite onto your hierarchy to create a new GameObject, then set up the animation for it — a reminder of how to animate sprites in Unity can be found here.
With your newly animated explosion set up, make sure you set the ‘Order In Layer’ property of the Sprite Renderer component to a higher number than the layer that your enemy is on — this will ensure the explosion happens ‘above’ the enemy rather than underneath it.
Create a prefab of the Explosion GameObject so that we can call it up whenever we need it.
With our explosion ready, open up the Enemy script.
We’ll need a reference for our prefab to be set in the inspector.
Finally, we need to ‘trigger’ the explosion when the enemy is hit. We do this in a slightly different way to how we create the enemy by applying the
Instantiate method to a variable. This allows us to then destroy the explosion GameObject once the animation is complete.
Destroy method, we are able to specify a timed delay for the method to be called, this is expressed as a float value in seconds.
Make sure you assign the prefab of your explosion to
_explosionPrefab in the Enemy script on the prefab of the enemy and you’re set for some Booms!