Introduction to Unity Animation

In this tutorial, you’ll learn the ins and outs of Unity animation by tossing pies at belligerent clowns. By Barbara Reichart.

Leave a rating/review
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

Animation Events: Trigger Code From Your Animation

Time to make the clown fit for duty again. A great way to do that is through Animation Events, which allow you to call functions from the game object’s script when an Animation Clip is running.

First, you need a script with a method that resets the clown’s size. Select the Clown in the Hierarchy. In the Inspector, scroll to the bottom and click Add Component. Select New Script and name the script ResetClown with C Sharp as Language. Press Create and Add.

Open the ResetClown script in MonoDevelop and add the following code:

void ResetClownOnHit () {
  gameObject.transform.localScale = Vector3.one;
  gameObject.GetComponentInChildren<CollisionBehavior> ().collided = false;
}

In this method, you set the localScale of the clown back to 1 to restore its original size. Then you use GetComponentInChildren() to reference the CollisionBehavior on the Skin and make sure that its collided variable is set to false. If you leave out this step, your clown will still move, but won’t react to collisions anymore.

Now you need to create an Animation Event that calls this method. Switch to the Animation View while the Clown is selected in the Hierarchy and pick the Hit animation clip. In the Time Line set the playback head to 1:30. If your Time Line is not visible beyond 1:00, use your scroll wheel to scale it down. Then click on the button Add Event.

Add Event

Double click on the marker for the Animation Event you just created.

Bildschirmfoto 2015-10-02 um 15.45.28

In the dialog window, select ResetClownOnHit().

Bildschirmfoto 2015-10-02 um 15.44.52

This creates an Animation Event that calls the method ResetClownOnHit() at 1:30.

Run the game. Now the clown shrinks, then resets and begins moving again, ready to be clobbered by cake once more!

FinishedAnimation

Where to Go From Here?

You can download the finished project here.

In this tutorial, you got a glimpse of the possibilities of Unity’s animation system. But much to learn you still have, young padawan. Some reading suggestions:

For now, enjoy the power you have gained over the animation system and make your games more beautiful and interactive. If you have any questions or comments, please join the discussion below!

Barbara Reichart

Contributors

Barbara Reichart

Author

Over 300 content creators. Join our team.