Adding a state behavior for destroying the explosion

If you hit play, the animation will play only once. However, the object won't be destroyed as we would expect. This can be done with a very simple script, which is a StateMachineBehavior. We take this script from the book Getting Started with Unity 5.x 2D Game Development (https://www.packtpub.com/game-development/getting-started-unity-5x-2d-game-development), which, once again, I suggest you read to get more insight into 2D game development. Thus, for the detailed explanation of this script, check out Chapter 4, No Longer Alone - Sweet Toothed Pandas Strike, of that book. Here, we will just see how to create and use that script, without explaining in detail how the StateMachineBehavior script works.

Create a new script, and name it StateMachineBehaviour_DestroyOnExit. Open it, erase all the code in it, and instead paste the following:

using UnityEngine;
public class StateMachineBehaviour_DestroyOnExit : StateMachineBehaviour {
override public void OnStateExit(Animator Animator, AnimatorStateInfo stateInfo, int layerIndex) {
//Destroy the gameobject where the Animator is attached to
Destroy(Animator.gameObject);
}
}

Save the script, and open the state machine of our explosion. Right-click the animation node, click Make Transition, then click the Exit node. As a result, you will see an arrow going toward the Exit state, as shown in the following screenshot:

Now, click the animation node, and in the Inspector, you should see an Add Behaviour button click it and add the script we have just created. Then, select the only Transition under the Transitions tab, and some settings will appear. Set Exit Time to 1 and Transition Duration to 0. Here is how it looks:

If we play the game now, the explosion should work. For more explanations of this process, you can read the book suggested before, but in any case, we will explore the animation system in the last project of this book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset