Ka Boom goes the Enemy
Objective: Add explosions to enemies when they are destroyed.
Create an animation for Enemy prefab and name the animation Enemy_Destroyed_anim. Add the sprite art, Enemy_Explode_Sequence from GameDevHQ FileBase, to the animation. Click on the Enemy_Destroyed_anim and uncheck loop time. Select the Enemy animation controller, noting Unity drops the _Destroyed on the controller, so rename it Enemy_Destroyed. Create an empty state by right clicking in the animator controller base layer, naming it Empty. Set Empty as the layer’s default state.
Create a transition from Empty to Enemy_Destroyed_anim. Uncheck has exit time and Create a trigger parameter OnEnemyDeath. Assign the condition for the trigger to OnEnemyDeath.
Reassign the controller to the Enemy prefab’s animator component in the inspector. Open the Enemy script and create a private Animator _animator variable, and assign it in void Start.
Create an EnemyDestroyed() function which handles starting the animation using _animator.SetTrigger(“OnEnemyDeath”). The function also halts enemy movement and collisions until the animation completes and the game object is destroyed after 2.7 seconds.
Call the EnemyDestroyed() function when the enemy is destroyed either by the laser or running into the player using the OnTriggerEnter2D function below.
The enemies now explode when they are destroyed.