Creating Enemy Explosions

Adding Visual Effects to your project will bring it to life. When adding simple things like an explosion will add extra depth and immersion. I mean what’s the fun of blowing up enemy ships when all they do is disappear and not explode in a glorious ball of fire?

In today’s article, we’ll be doing just that. But instead of creating multiple explosions for our enemies and other objects, we’ll be creating one explosion with its own logic and reuse it as a prefab for all game objects.

Prefab Set-up

We need to create an empty object in the Hierarchy and name it “Explosion”. After that, click on the Animation window, create a new animator component, and then drag the explosion sprites to the animation window. If everything has been set up correctly, you would have an explosion effect on the screen. if you’re happy with the animation, then next we’ll be creating a new script called “Explosion” in the Scripts folder. Drag the script to the Explosion object and drag the explosion object into the prefabs folder.

The Code

Creating the code logic for the Explosion is fairly straightforward. Since we’ll be creating the explosion through code as an instantiated prefab, we’ll need to destroy the object after the animation has completed. I’ve chosen to create a function called “Destroy()” and manually running that function on the last frame of the animation.

Animation Events

In the Animation window, you’ll notice a small icon like a pin and a small + icon. This will create an event at the frame you’re currently on. These events are used to trigger functions in a script that’s attached to the same object as the Animator. Since we’ve only created one function called “Destroy()” we can now set the event to run that function, and cause the object to be destroyed on the last frame of the animation.

Wrapping Up

We’ve now created a modular explosion effect that we can use throughout our game and instantiate it wherever we need explosions to happen. And best of all the explosion will clean itself up so that we don’t have hundreds of “used” explosions filling up and slowing the game.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store