Explosion Effects in Unity through Animation
In order for something to get a destruction effect through animation, the first need is to have the 2d explosion sprites in place.
Once they are, head to the game object on which that effect is needed and attach an animation.
From here, a few configs are needed to have the effect occur at a right time.
The aim of the exercise here is to play the animation only when the enemy collides either with a laser bullet or the player. Hence, the animated effect has been attached to the enemy object.
- Go to the animator window and it should show the following pattern if the animation has been applied correctly on the game object.
- Here, right-click and add an empty state (rename as per choice) which is going to behave as a bottleneck for the animation effect to pass through.
- Again, right-click on the newly created state and make it a default state.
- Make a transition from the new state to the animation state.
- Select the “+” symbol in the animator window and add a trigger parameter with a name of choice. (Bool can work also with setBool( )).
- Click on the transition arrow in between the newly created state and the animation to verify what will happen when the state shifts to the animation. (This is the hook!)
Now, you have a switch in hand that should be turned on upon a collision. So, open the associated script with the game object that is holding the animation.
- First, get the handle of the animator component in the script.
private Animator _explosion;
- Use the SetTrigger(“xxxx”) method to enable the animation. the argument in this method is the name of the trigger that was created in the steps above.
For making the collision look smoother, there are few house cleaning tasks.
- First, untick the “Has Exit Time” option that basically means a state will only get transferred after full completion.
- Second, reduce the speed of the game object that gets destroyed.
- Third, disable the collider component as soon as the collision occurs so that the other object does not get affected if there are collision penalties set in the game.
- Fourth, the animation needs a few seconds to get displayed and therefore, delay the destruction of the object for a few seconds.
public void _TriggerAnimation()
{
_explosion.SetTrigger("OnEnemyDeath");
_speed = 4.0f;
this.gameObject.GetComponent<Collider2D>().enabled = false;
Destroy(this.gameObject, 1.5f);
}
- Finally, call the method in the right place.
Let me show you the final result here :)
Thank you very much