Learn to code by making 2 D space shooter.
Objective: Add Enemy explosion and Trigger it in code when enemy Killed.
To do this, we need to create an enemy explosion inside the game scene.
The first step Open the animation window, by going to window < animation< animation.
Select the enemy in prefab or drag enemy in the hierarchy and select it, go to animation click create button rename animation then go to the sprite select the first frame hold down shift select the last frame to drag them to animation dope sheet.
If we play this we may have more than one issue, our animation may not play when starting the game to solve this select our enemy prefab go to the inspector below you will see the animator component added but there is a missing reference to the controller.
But when we play enemy destroyed automatic, we want to destroy the enemy using code to solve this, go to the animation folder double click animator controller to open the animator window.
Create an empty state rename it as empty and set it as a default state, now the enemy won't destroy itself automatically.
Now we want to transition to enemy_destroyed animation but only when the enemy is hit by laser or Player.
Select empty state and create a transition to enemy_destroyed, if we leave like this it after complete empty state will trigger the explosion right away.
To trigger animation through code we need to create a parameter that will give the ability to call animation when we want through code.
In the animator window to the left left-click the parameter tab hit plus button then choose the trigger option then rename it, now select the transition you created from empty to Destroyed_anim go to the inspector there is a condition option hit plus button the condition will be filled automatically.
To Trigger animation in code, we use animator.SetTrigger method but before we need animator reference variable.
Then we can call that method when the enemy is hit either by a player or laser.
Note: Make sure the parameter spelling is correct it is case sensitive.
If we Play we will have issues when our animation is not played or not seen played.
This is because the object is destroyed at the previous frame before our animation finished played, we need to tell destroy method to wait until our animation is finished.
To know how long our animation plays go to the animation folder select animation, go to the dope sheet you will see the time in seconds.
The destroy method has a parameter that passes time so gives more time for animation to finish.
Play with second on destroying to make things look cool.
Last let's make thing smooth cos animation seem to delay, to fix this select transition from empty and uncheck has exist time.
And make sure to uncheck loop time to avoid animation to repeat, select
This is how to trigger animation through code, see you in the next article.