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 inside Unity, work with imported animations, learn to use Unity Animator and control the animation parameters. In this tutorial, we will cover all these topics from scratch.

Watch as video

Unity Animation vs Unity Animator Controller

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.

Simply put, any visual action related to a game object 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 Clip 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. You can use the Unity animation timeline window to create some basic animation like rotation, or sprite animation from sprite sheet, which we have covered in our 2D animation tutorial.

To create a new Animation, use the steps below

  • Select the object you want to Animate in the Hierarchy.
  • Go to Window>Animation>Animation or press Ctrl+6.
  • In the Animation timeline window, click create to create a new animation.
  • Save it with the name of your choice. Click the record button (red circle on the left top) on the Animation window.
  • Click on different timeline positions and move your game object to the required place.
  • You can use the animation curves under the curves tab to smooth out the animation motion.
  • Click the record button again after you are done animating.
  • Press the play button in the animation window, to preview it in the scene view.
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 state machines 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 at what time.

You can setup a state machine for an object to control the Animation clips. Here is an example of a state machine to switch between rest animation and jump animation.

Unity animator Window showing different animation states

Playing an Animation clip

Unity Animation component and “Animation.Play()” function have been deprecated. Do not use them to play animation clip. They are kept to maintain backward compatibility with the old Unity Animation system.

If you have a single animation clip, then attach the Animator component to the game object and follow the steps below.

  1. Open the Unity Animator by going to Window>Animation>Animator.
  2. Drag and drop your animation clip to the Animator window.
  3. Play the game and Unity will automatically play the animation clip.

If you have more than one Animation clip then use the steps below to setup your Animator.

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. If not, drag and drop the animation clips inside the Animator window.
  4. The one in orange color is the default animation state and will play as the current state 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 an animation transition from one state 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 transitions. 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, then 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”.

Play animation from script in Unity

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 state inside the Animator window which you want to have variable speed. Go to the Inspector.
  • Set the speed value to a number greater than zero. One is preferrable.
  • 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

If you have multiple animations for a single object 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 attack 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 state machine 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 Animation events 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));
    }


    
}

Understanding Animation Blend trees

Unity game engine allows you to create multiple state machines but for a character model with multiple animation, the state machine might become too complex. This is where blend trees come into picture. You can combine multiple animation clips into a single blend tree that can be controlled using a single parameter.

For example, if you have a walk, run and sprint animation for your character, you need to switch between each of these states based on the character speed. You can add all these to a blend tree and use the character speed as the parameter to control which animation plays.

In Unity animation, using 3d character creation services can improve the look and feel of your projects. These services provide detailed character design, making sure each character looks good and works well in Unity. By working with 3D character experts, developers can choose from many ready-made models or ask for custom characters. Combining good character design with Unity’s animation tools can make games feel more real, attracting players with realistic movements. As more people want to outsource the process of creating game characters, using 3D character services will become more important for developers.

Creating a blend tree in Unity

Open your Animator controller window and right click>Create State>From New Blend Tree

Adding a new blend tree

You can rename your Blend tree using the inspector window. Double click the Blend tree to open a new state machine window.

To add animation clip to your blend tree. Select the Blend tree node and right click>Add Motion.

adding motion to blend tree

You can add multiple motion to a blend tree. Now drag and drop your animation clip to the added motion in the inspector window.

A blend tree with motions

To set the threshold for the animation states, uncheck automate thresholds and then enter the value in the inspector. For the above example, we have entered 0 to 0.5 for Player_jump and 0.5 to 1 for Rest. You can use the slider in the animator window to check the transition.

entering thresholds for blend tree

We have covered all the basic of Unity Animation and the Animator component. If you have any other questions, feel free to leave them in the comment box below.

Now let’s go ahead and learn 2D animation in Unity.

Leave a Reply

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

Discover more from VionixStudio

Subscribe now to keep reading and get access to the full archive.

Continue reading