You’ve got your game, enemies are coming at you fast and furious. You’re blasting them to pieces but what’s that? No explosion? No feedback? No good! In this tutorial we’ll cover triggering enemy explosions in the context of a 2D game, this should also be valid for a 3D game but with a bit more tweaking.
Start by opening an existing Unity project or starting a fresh one. Here’s a test sprite we can use courtesy of Open Game Art (here) Drop it into your project folders and let’s get started. Make sure the sprites are labelled as such by Unity. You can do this by highlighting all the textures and then selecting Sprite (2D and UI) under Texture Type in the Inspector.
Next you’ll want to drag the first sprite of the bomb into the Hierarchy. It’ll act as the base object like an enemy. Next we’ll create the animation. The quick way to do this is just by highlighting all of the sprites and dragging to the Hierarchy but you can do the “proper” way by checking out my article on animating sprites (here) like so.
Be sure to save the animation and name it something like “Explosion” then prefab the animation object in the hierarchy, we’ll use that later when we trigger the explosion via script. Also make sure to turn off the loop time of the animation in the inspector when you click on the animation clip. Unless you want it to constantly loop then leave it checked.
Now we’ll go ahead and create a script named EnemyExplosion and attach it to the bomb in the scene. This will allow us to trigger the explosion and then assign the explosion prefab to the enemy. Here’s the script in it’s full entirety below with comments.
Now in the inspector make sure the explosion prefab is slotted in and then let’s fire it up and see what happens when we hit ‘D’ on the keyboard.
Kaboom! A seamless enemy explosion. This was a very very basic implementation of this kind of explosion, in a real game you would have an enemy explode on contact with a projectile fired from a weapon or when they die like in Atomic Shooter my minimalist SHMUP.
However this should give you the tools you need to take this knowledge and put it into your own games. Until next time, happy coding.