Creating Explosions in Unity
In today’s article, I’ll be going over how I implemented the explosion animation when an enemy gets shot by the player.
In the Unity Editor, I have the Enemy game object selected in the Scene hierarchy, open the Animation tab (can be found under Window -> Animation -> Animation), and create a new Animation Clip named Enemy_Destroyed
With the Enemy game object selected, I drag all explosion frames onto the Animation Dopesheet:
Next, I Create 2 states in the Animator tab:
- Empty state represents the first state the Enemy game object goes into from the Entry state.
- Enemy_Destroyed state gets triggered when
onEnemyDeath
trigger is set to true.
To create a Trigger parameter, select the Parameters tab, the + button, and select Trigger. In my case, I named the trigger onEnemyDeath
The Code
In the above code, delayDestructionRef
is a Coroutine type where I assign it to the StartCoroutine()
function on line 13. To transition into the Enemy_Destroyed state, I call animator.setTrigger("onEnemyDeath")
which is the condition required to transition between Empty and Enemy_Destroyed states:
Delaying the destruction of the enemy is important here because the Enemy game-object will not have the chance to play the destruction animation as it is part of the same game object being disposed of. To avoid hard-coding in the number of seconds the animation will take to complete as the delay to destroy the Enemy game object, I use animator.GetCurrentAnimatorClipInfo(0)[0].clip.length
.
Getting Animation Length in Seconds
GetCurrentAnimatorClipInfo(int layer)
function takes in a layer int parameter. Based on the Unity Docs, it returns an array of `AnimatorClipInfo` objects that contains information about each animation in the array.
- 0 is assigned in the parameter because that represents the Base Layer containing the state machine that has the
Enemy_Destroyed
state - I access the array by using the [] operator to access the array by index. I set it to 0 here because I know that this particular object only has 1 animation clip
.clip
returns the animation clip data.length
is the number of seconds the animation clip lasts
In the DelayDestruction
coroutine, I wait for 1 frame to ensure the Enemy_Destroyed
state is active when the trigger onEnemyDeath
is set and delay destruction of the Enemy until the explosion animation effect completes.
Not delaying the destruction will cause the animation to not play out as the Destroy game object function will immediately destroy it after the Update
function completes its frame.
Thanks for reading :)