Getting Started Guide to Unity Animation and Animator

As a Unity developer, you should know the basics of Unity Animation. By basics, it means you should be able to create basic animations, work with imported animations, learn to use Unity Animator and control the animation parameters. In this tutorial, we will cover all the basics that you need to know.

As soon as you start learning about Unity animation, you will start seeing the word animator. So, it’s better to learn about the difference before you start making animations in Unity.

Unity Animation vs Unity Animator

Simply put, any action related to a Gameobject is referred to as Animation and the controller used to control the actions is called Animator.

Let’s try to understand this in detail. But before that you should know the following

  1. A game object can have more than one animation in Unity. For example, walking, running, jumping etc.
  2. You need a controller to control which animation plays at what time.

Now with that in mind. If you want to play a walk animation while the player is moving slowly and play the run animation when the player is moving fast you can use the Unity animator to make that switch.

Let’s see this in action by creating simple animations and switching between them.

Creating an Animation in Unity

Animation is also referred as Animation clip in Unity. You can create an animation or import it from other software like Blender. All Animation files are saved as a dot anim file.

To create a new Animation, use the steps below

  1. Select the object you want to Animate in the Hierarchy.
  2. Go to Window>Animation>Animation or press Ctrl+6.
  3. In the Animation window, click create to create a new animation.
  4. Save it with the name of your choice. Click the record on the Animation window.
  5. Click on different timeline positions and move your game object to the required place.
  6. Click the record button again after you are done animating.
Unity Animation window

You should see this Animation clip in your project folder.

You can create multiple Animation clips for a single game object. For the sake of this tutorial, create a Rest animation where the player just stays in one place and a Player_jump Animation in which the players y position changes.

Animator in Unity

When you create a new Animation, Unity will attach an Animator component to your game object. This controls which Animation clip needs to play. You can do all sorts of things with the Animator. Here are a few examples

Unity animator Window

Setting the Default State in Animator

  1. Open the Unity Animator by going to Window>Animation>Animator.
  2. Select the game object in the Hierarchy window to which contains the animations.
  3. You should see the animation clips as shown in the image above.
  4. The one in orange color is the default animation state and will play once the game starts.
  5. If you want to change the default state, select the state that you want to be the default animation. Right click and select, set as default.

Changing Animation States in Controller

You can switch between states using the Unity Animator. To make a transition from one scene to another. Right click on the first state and select make transition. Now select the second state to which you want to transition. Now you should see an arrow between the state symbolizing the transition.

Creating transition in Unity Animator

Be careful on how you make the transition. If you make the transition from Player_jump to Rest and no transition from Rest to Player_jump then the Player_jump animation will never play.

Conditions for Animation transition

You can set the condition of Animation transition. To set the condition, select the arrow symbolizing transition and you should see the transition properties in the inspector window.

Animation transition parameters in Unity Animator

If you want the animation to transition to the next state after it has completed playing then just check the box, “Has Exit Time”.

If you want to have certain conditions which can be set from a script the you can use the + sign to add the conditions in the conditions box.

Before adding the conditions, you need to create parameters in the Unity Animator using the steps below.

  1. Select the parameters tab in the Unity Animator Window.
  2. Click on the + sign and select the type of parameter (Float, int, bool and trigger).
  3. Give it a name, default value and save it.

Now you can go the transition properties and add the condition.

Pro Tip: If “Has Exit Time” is checked and the condition is true, the transition will only happen after the clip has ended playing. If you want the transition to happen immediately on Condition true then uncheck “Has Exit Time”.

Setting the Animator Parameter from a script

After you have created an Animation parameter you can set it from the script using the steps below.

  1. First create a variable of type Unity Animator.
  2. Get the Animator component using GetComponent.
  3. Set the parameter using SetFloat, SetInt, SetBool and SetTrigger.

Here is an example script to set the value 3.5 to the parameter “myFloat”

using UnityEngine;

public class AnimatorTest : MonoBehaviour
{
    Animator anim;
    // Start is called before the first frame update
    void Start()
    {
        anim=GetComponent<Animator>();
        anim.SetFloat("myFloat",3.5f);        
    }

}

Looping An Animation in Unity

  1. Go to the project window in the Unity editor.
  2. Select the Unity Animation clip that you want to loop.
  3. In the inspector properties of the clip, check the loop time parameter to play the animation in a loop.
Parameter to loop animation

Slow down or Speed up Unity Animation

Animation speed needs to sync with the player movement to make it look natural. We will see how to decrease or increase the animation speed to match the player movement.

Using a fixed number

If your animation is set for something that has a fixed speed then you can change the animation speed once and it will remain synced.

  • Open your Animation controller in the Animator window. You can access the animator window from Window>Animation>Animator.
  • Select the animation you want to slow down or speed up.
  • Go to the Inspector window.
  • You will find a parameter named speed.
  • Enter value less than 1 to slow down animation and value greater than 1 to speed up.

Setting a variable speed to animation

Animation parameters in Unity Animator

If you have a character with variable speed then the animation speed needs to change based on the character’s moving speed.

You need to add a float variable to your animator for this purpose.

Creating a parameter in Animator
  • Now select the animation which you want to have variable speed. Go to the Inspector.
  • Remember, you need to have the speed value set to a number greater than zero.
  • Check the parameter box near multiplier and select the float variable you just created.
  • Now your animation speed will change with the float variable.

To set the float variable use the code below

anim.SetFloat("Mov_speed",character_speed/Time.deltaTime);

Now you should be able to set the animation speed based on your requirement.

Randomizing Animation in Unity

You have multiple animations for a single state and want to play the animations randomly? Want to start an animation from a random frame? Want random animation speed? In this section, we are going to see how to randomize all aspects of animation.

Playing random animation

I am Using Unity 2021.1.13 along with HQ Fighting Animation FREE asset from Unity asset store for this tutorial

Start a new project and import the assets into Unity. There is a demo scene included with the asset. Open the demo scene and remove the script used to control the animation state. We are going to use our own script to randomize the animation state.

Open animator by going to Window>Animation>Animator. Delete other states and keep only the attach states. There are 4 attack states in our controller that we will play randomly. Remove all the parameters and create a new integer variable called ‘Attack_no’.

Set up the transition from Idle to each state based on different Attack_no as in the image below.

Unity animator window
animation random condition

Set Attack_no from 1 to 4 for each attack. Now let’s add a script to randomize the integer and play different animation at random.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Anim_random : MonoBehaviour
{
    Animator anim;
    bool generated=false;
    // Start is called before the first frame update
    void Start()
    {

      anim=GetComponent<Animator>();  
    }

    // Update is called once per frame
    void Update()
    {
        if(anim.GetCurrentAnimatorStateInfo(0).IsName("Idle") && !generated)
        {
            anim.SetInteger("Attack_no",Random.Range(1,5));
            generated=true;

        }
        
    }
    public void animation_event()
    {
        generated=false;
    }
}

The transition between animation states takes more than one frame. So multiple random numbers get generated. To avoid this, use a Boolean and set it as true when a random number is generated. You can set it to false once the animation clip is played.

The above script uses an Animation event for this purpose. An animation event is used to call a public function from the script.

Adding an Animation event

To add an animation event, follow the steps below.

  1. Create a public function with the conditions you want to execute. In our case we want to reset the Boolean to false.
  2. Select the animation clip from the project window.
  3. Find the Events tab and click on add event (it’s a symbol on the left top).
  4. Drag and drop the script to the object reference.
  5. Enter the name of the function without “()” in the Function Variable.
animator event

Start Animation at a Random frame

To play an animation clip from a random frame you can pass the optional third parameter normalized time of Animator.Play() function. Normalized parameters taken a float in the range 0 to 1. Depending on the value to the normalized time the animation stars playing. You can randomize this value to start animation at random frame.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Anim_random : MonoBehaviour
{
    Animator anim;

    // Start is called before the first frame update
    void Start()
    {

      anim=GetComponent<Animator>();  
      anim.Play("Jab",-1,Random.Range(0.0f,1.0f));
    }


    
}

Randomizing Animation Speed in Unity

Animation speed can be changed from the script using the Animator.Speed parameter. It takes a float value. Make sure not to make the top value too big unless you have a very slow animation clip. Here is a sample script you can use.



using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Anim_random : MonoBehaviour
{
    Animator anim;

    // Start is called before the first frame update
    void Start()
    {

      anim=GetComponent<Animator>();  
      anim.speed = Random.Range(0.0f,4.0f));
    }


    
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.