See the Tutorial List

Animation and Animator in Unity 3D

Animation is one among the two components of a game, which brings it to life (the other being audio). Unity’s animation system is called Mechanim, and its power lies in bring humanoid models to life. In previous versions, another component called “Animation” was used, but it has now been depreciated in the recent versions of Unity.

animation Option images

Here in this tutorial we will see the basics of how the Animator is used for creating animations. We will make a mini game module of a door that opens on us pressing space and then closes if we press space again. So lets start our journey and hope in the end, we all get through that door.


1. Creating our Environment

In this module we will set up our environment. This means that we will be creating:

  • The base/ground
  • A 4 walled structure
  • Our door
  1. To create the base right click on the Hierarchy panel>3D Objects>Cube. Double click on the Cube object in the Hierarchy. The Scene Window focuses on the cube.
  2. Now in the Inspector panel, you will see the transform component. Make sure the position and rotation of the cube is (0,0,0) and the scale is (1,1,1). Change the scale values to (5, 0.5, 5). This will be our floor. Rename the object “Floor” (without quotes) by selecting the cube in Hierarchy, pressing F2 key, typing the name and pressing enter.
  3. Scaling And Rotating images

  4. Similarly create 3 more cubes and arrange them in such a way that they make 3 walls for the floor. This is a task for the reader.

    Scaling And Rotating images

  5. Now for the door. Basic doors can be of 2 types, sliding or hinged. We will go for the sliding door. Now similar to the last step create another wall to make a room without a roof. Name the fourth wall as “Door”. This will be our door.

2. Setting Up Our View

This module is for those who do not have an Animator panel open. If you do, skip to the next section.

To open the Animator panel, click on the Window option on the menu bar and from the drop down list select Animator.

Also from the same Window menu, select the Animation option to open the Animation panel.

We will use both of these to create our sliding door animation.


3. Creating Animations for the Door

For creating animations, we first create the animation movements, then we order those movements in the form of a state machine (look it up!) so that we are able to transition from one state to another. Do not be intimidated by the animator figure below. After this tutorial, you would be making these in your sleep.

Animation Door images

Now for creating the animations

  • Select the Animation panel and click on Create.
  • Name you animation “DoorOpen” and save it in the Asset folder. Similarly make another animation called “DoorClosed” and save it.

    Save Door Open Option

    Save Door closed Option

  • Select the created animation files one by one and uncheck the “Loop Time” option.

    Inspector door Option

  • Now pay attention to this point as it is the step that creates magic. Select the “DoorOpen” animation in the Animation panel. You wills see a time line. This is called the Dopesheet (maybe cuz its ‘dope’.... I don’t know). It will act as the timeline of the things that will happen during the animation.

    Dhopsheet images

  • Click on the Add Property button and select Transform >Position. Here we can see that 2 diamonds have formed on the time line. These depict keypoints at which we know the properties of the object. Given a set of keypoints, Unity automatically interpolates and generates the movement that is to occur between these two keypoints. Keep this feature in mind as you move ahead.

    Add PRoperty images

  • On the timeline above, there are numbers written depicting the time. Click on the number above the keypoint (diamond) at the end. A white line should appear over the keypoint. This denotes that the modification of that fraction of time will take place, which is under the white line. Now click on the red button to start recording the motion.

    Add PRoperty images

  • Using the transform tool, move the “Door” object in the Scene View such that it has reached an open state according to you. Press the Record Button again to stop recording. You can check the animation by pressing the play button that is besides the record buttom.

  • Similarly create the “DoorClosed” animation. This is a task for the user.

    Door Closed  images


4. Using the Animator State Machine

Now that you have your moving doors, we have the problem of making them move according to our will. For this, we have to have an understanding of the Animator and what it actually does.

Like it was mentioned above, the Animator takes care of the transferring of one Animation state to another. For exmple, imagine yourself playing a First Person Shooter game like PUBG or CS: GO. Here if you are only pressing W, the player character walks or jogs, but as soon as soon as shift is pressed in conjunction with the W key, the player seamlessly bursts into a sprint. This change from “Walk State” to “Sprint State” is what the Animator takes care of.

Coming back to our door, if we open the Animator we will see various colored boxes with stuff written on them like “Entry”, “Any State”, “Exit”, etc. These are the various animation states.

Among these you’ll find an orange arrow starting from Entry state to the DoorOpen state. This arrow (or any such arrow) depicts a transition from one animation state to another. Lets see what the various states signify.

  • Entry: Entry refers to the state of animation when the scene first comes into existence.
  • Exit: This state is used to end the animation and begin again at the Entry state. To make it simple suppose your transition ends in state "foo". Try drawing a transition from "blablabla" to "Entry". You just can't.

    Now If you really need to do that then that is when you use "Exit".

  • Any State: Any State is a special state which is always present. It exists for the situation where you want to go to a specific state regardless of which state you are currently in. This is a shorthand way of adding the same outward transition to all states in your machine. Note that the special meaning of Any State implies that it cannot be the end point of a transition (i.e. jumping to “any state” cannot be used as a way to pick a random state to enter next).

Also you will see an arrow going from the Entry state to the DoorOpen state. This is not what we want. Here the door opens as soon as the scene starts. What we desire is that the door waits until we command it to move. So we need an “Idle” state, i.e. a state with no Motion attached to it.

Animation layer Images

  • To do this,right click on the Animator panel space and from the drop down, select Create State>Empty.
  • Now rename this “New State” state to “Idle” (do it yourself).
  • Now we need Idle to be the Default state (state transitioned to after Entry). TO do this right click on Idle and select the Set as Layer Default State

    Animation layer Images

Now for the transitions. Transitions refer to the transference of control from one state to the next. The arrow in orange that you see represents a transition.

To create a transition, right click on the initial state> from the drop down select Make Transition>Click on the next state.

So try to create a working state diagram yourself and check it whether it is correct or not with the image below.

Animation layer Images

Its not over yet. Here if you press play, the door opens and closes automatically. This is because our transitions are condition-less. Condition-less transitions occur as soon as the initial state has finished playing its animation once. We need control here. So we apply conditions to the transitions.

To apply conditions, we require to set a parameter which toggles the door open or closed. To do this :

  • select the Parameter tab from the top left corner of the Animator panel.
  • Click on the + icon below and select the Boolean option from the drop down list.
  • Rename it to “isDoorOpen” (do it yourself).
  • We select a boolean as it will be easy to depict the open and closed states of the door using it.
  • Animation layer Images

Now to apply the conditions to the transitions:

  • Select a transition by clicking on the arrow.
  • In the Inspector panel, click on + in the Conditions option.
  • Set the value of the condition acoordingly.

The value of the transition 1, 2, and 3 for “isDoorOpen” are true, false and true respectively.

Animation layer Images

Hence we are done with setting up our conditions. We will be triggering these transitions via code.


5. Writing the Code

  • Create an empty object called “Door Manager” and add a new C# script to it called “DoorManagerScript”.
  • To add the script, select Add Component > New Script > Name the script “DoorManagerScript” > Press Create and Add
  • In the script, type the following code and save it:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DoorManagerScript : MonoBehaviour 
{
    public Animator anim;

    private bool trigger;

    void Start()
    {
        anim.SetBool ("isDoorOpen", false);
        trigger = false;
    }

    void Update()
    {
        trigger = anim.GetBool ("isDoorOpen");
        
        if(Input.GetKeyDown (KeyCode.Space))
        {
            if(!trigger)
            {
                anim.SetBool ("isDoorOpen", true);
            }
            else 
            {s
                anim.SetBool ("isDoorOpen", false);
            }
        }
    }
}

6. Through the door and to the other side

Well I would like to congratulate you on creating your first moving object in Unity. And what’s more it works as per your command! Great job. This was just a glimpse of the power of the Mechanim system can do if its in your capable hands.

So press play and see the magic happen when you press the space bar.

Animation layer Images