How to play an animation on key press on Unity 2018

play animação movie like

Learn how to control your animations on Unity utilizing the Animator Controller. Easily execute yours through a trigger parameter.


Júlio Rodrigues ·

There are several ways to play an animation on Unity. The most common one is what will be taught in this tutorial. You'll learn how to use Animator Controllers.

It's also possible to utilize the Playable API to achieve this result. The overhead is way smaller but this alternative is considered advanced, avoid doing it if you're just getting started at C# scripting on Unity

On that puzzle, there are a few pieces that need to be understood. First, let's see a step-by-step procedure on how to play an animation and the description of each of these pieces.

This tutorial has been developed and tested using Unity 2018.2

A step-by-step procedure on how to play an animation

  1. Import the 3D model
  2. Import the animation (or create it inside Unity)
  3. Create an Animator Controller and configure it to have a trigger parameter.
  4. Utilize the component Animator in a script to activate the trigger create on 3.

If you want to do that for a 2D animation the process is slightly different, but this tutorial should you help on that task too.

For steps 1. and 2. it's sufficient to drag and drop the assets to your Assets directory of your project that Unity will do the proper import. You can also download directly from the Asset Store.

Before going to steps 3. and 4. let's better understand what they are about.

What is an Animator Controller?

Unity utilizes a sophisticated system of control, transition and blending of animations. In the past, this system was largely known as Mecanim.

For playing just a single animation it looks like a lot of work for a small return using this sophisticated system. When you start to use various animations for the same character and want the animations to smoothly blend from one another, you'll soon realize that this workflow is indeed really interesting and effective.

The center of this control is defined by the Animator Controller. An Animator Controller is an asset containing all the information on how to manage and blend the different animations your character (or object) posses as well as the transition between them. These transitions are described through a finite state machine. Do not be scared since to what we'll build here the machine will be really simple.

saved animator controller asset

Se você já possui os seus clipes de animação importados, o Animator Controller os usa para controlar qual (quais) animações vão ser executadas e em que momento dependendo do atual estado deste Animator.

If you already have your animation clips imported, the Animator Controller will use them to control which animation (animations) will be executed and when depending upon the state of an Animator.

States

You'll have states like idle, walking, shooting, dead, etc. Between these states the transitions. In general, a character starts on an Idle state and might change it to some other based on a parameter and transitions conditions.

A state machine with the states:: Idle (default state), Walk, Run and Jump .

Parameters

The parameters of an Animator Controller are the variables controller via script that allows you to interact with the animator. Going back to the Idle case -> Walking, we could have a parameter speed and if speed is greater than or equal to 0.1 then we would transition from Idle to Walking.

There are 4 types of parameters:

  1. Integer. It's a whole number.
  2. Float. A (approximated) real number.
  3. Bool. A true or false.
  4. Trigger.A special true or false which turns off automatically.

As they saw that the parameter bool was being used most of the time turning it off right away from true to false, as in the case of a shooting animation, the unity developers create the trigger type that does this kind of work to us automatically.

In that tutorial, we'll use a trigger parameter.

Transitions Basics

Parameters are the base of transitions. For each state, you'll create transitions between them and the conditions for each of these transitions.

On that example we created the transition Idle -> Walk in the case of the parameter "Horizontal" is bigger than 0.1.

Transitions might also happen automatically in the course of time. This option is called Exit Time. On settings, it's possible to control the Exit Time.

Note that Exit Time does not use absolute values in seconds, but relative values from 0 to 1, that is, if we have an exit time value of 0.8, in the first frame in which 80% of that animation is executed the transition will start.

Creating the Animator Controller We Need

An Animator Controller is an asset that needs to be saved in your project. Right click on your project tab and look for Create -> Animator Controller, give a name for your animator controller and press enter.

You can create states for your Animator Controller by dragging and dropping animation clips from the Project tab into the Animator window (opened through a double click on the asset file) or by using the right button Create State -> Empty.

Animation States

Drag & Drop your animation inside the Animator window to create the state of your animation.

On that example, I've also dragged & dropped an animation for the Idle state so the character looks more natural while standing still.

Parameter

Now that we have the states it's necessary to create a parameter of the trigger type that will be used in the Idle -> Attack transition.

Click on the + button of Animator window the superior left.

Choose the type Trigger and name it Punch

Transition

If your Idle state is not orange right click it and choose Set as Layer Default State. With that done press the right button of your mouse on the Idle state and choose Make Transition, now choose the target state.

transition created and selected

With the outbound transition selected, in the Inspector tab (outside the animator window), add a condition pressing the + button. Since you have only a single parameter your transition condition is already configured. Be sure to uncheck the Has Exit Time option just above.

Creating and configuring the character to use this Animator Controller

Drag the asset of your model into the Hierarchy tab or inside the Scene window. In the Inspector add the component Animator. Now drag & drop the controller that you just created to the field Controller

You may need to set up an avatar for your model. If you downloaded it from the asset store it's highly likely that your avatar will come ready to be used. You only need to click on the little circle to the right of the avatar field and choose the appropriate one.

Creating the script and triggering the trigger

With the Animator configured for your character, we finally reached the final step where we trigger the trigger via script. Select your character in the Hierarchy tab, choose Component and type something like PlayerController, choose Script and press Create and Add.

It's always a good idea to leave your project organized. Move that file you just created in the Project tab to some other directory where you concentrate all your scripts.

In order to use the Animator component we created, our script needs to make reference to that component somehow. Create a public variable of the type Animator in your script called animator.

using UnityEngine;

public class PlayerController : MonoBehaviour {

public Animator animator;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

}
}

Then drag & drop the component Animator to the field Animator of your new script.

We'll choose the J key to trigger our animator controller. Inside update, we must verify if the player pressed such key.

void Update () {
if (Input.GetKeyDown(KeyCode.J)) {
animator.SetTrigger("Punch");
}
}

Input.GetKeyDown will only return true in the exact frame the player started to press the key. This prevents the animation from restarting on every frame what would happen if we had used the method Input.GetKey.

Final Result: unity-chan (Unity's Japanese mascot) executing a two punches animation.

Where to go now?

Excellent! You're now able to play your animations using the unity's animation system. But I think that you want to continue on your journey, right? This system is really rich, I'll suggest a few exercises for your continued practice:

  • Make the back transition to Idle from Attack using Exit Time
  • Create more states and its transitions with at least 3 animations.
  • Explore the official Unity documentation about the subject always trying to replicate what is being explained.

If you have any questions leave them in the comments section below. If you liked this tutorial your friends might like it too, share it with them!

Detailed Unity Tutorials in your inbox

Subscribe if you want to receive articles and tutorials like this one right in your inbox. 

Classify in:
  • unity
  • animator controller
  • tutorial
  • getting started
© Bladecast 2018. All rights reserved.