Triggering an Explosion Animation in Unity3D
Objective: Trigger an explosion animation when the Enemy Prefab is destroyed.
Step 1: In the Game scene, select the Enemy Prefab in the Project window and double-click to open it in the Prefab Scene view. Open the Animation window, click the Create button, and save a new .anim file called Enemy_Detroyed_anim within the Animations folder. In the Animator window, click the record button to activate the record mode, drag the desired animated Sprite frames into the Dopesheet timeline, and turn the record mode off.
Note: Be sure that the Enemy_Desroyed_anim animation controller (called Enemy) is attached to the Enemy Prefab‘s Animator component.
Step 2: Exit the Prefab Scene view, and double click on the Enemy animation controller in the Project window. This will open the Animator window to show the flow of the animation states. Right-click within the Base Layer of the Animator window and create an Empty State. In the Inspector window rename the New State to Empty. In the Animator window, right-click on the Empty state and select Set as Layer Default State. Right-click the Empty state again, select Make Transition, and click on the Enemy_Destroyed_anim state.
Step 3: In the Animator window, select the Parameters tab on the left side of the window, click the + sign to add a new Trigger parameter called OnEnemyDeath. In the Base Layer view, click the Transition connection between the Empty state and the Enemy_Destroyed_anim state. In the Inspector window, click the + sign under the Conditions list to add the OnEnemyDeath parameter. Then, uncheck the Has Exit Time option and set the transition Duration to 0. This will ensure that the Enemy_Destroyed_anim interrupts the Empty state cycle so there is no delay with starting the explosion animation.
Step 4: In the Enemy Script, create a new private variable of type Animator called _enemyAnim. Then in the Start() method, assign the Enemy Prefab Animator component to the _enemyAnim variable and null check.
Step 5: in the OnTriggerEnter2D() method, use SetTrigger(“OnEnemyDeath”) to trigger the animation and then set the _speed variable to 0 within both if statements after the Laser Prefab or the Player GameObject collide with the Enemy Prefab, but before destroying the Enemy. This will stop the Enemy Prefab from traveling down the screen and damaging the Player once the explosion animation begins. Lastly, add a float value of the length of the animation, in this case, 2.2f, to the Destroy statement to delay destroying the Enemy Prefab until after the animation is complete.
Save the script, go back to Unity, and the explosion animation will trigger when the Player and Enemy collide or when the Laser and Enemy collide.