Lesson 45 +10 XP

Animator Controller & State Machines

Animator Controller & State Machines

To play and manage multiple animation clips on a GameObject (e.g. transitioning from Idle to Run when moving), you use an Animator Controller.

Animator Controller Asset

An Animator Controller is a State Machine asset. It defines:

  • States: The animation clips (e.g. Idle, Run, Jump).
  • Transitions: The connections that allow moving from one state to another.
  • Parameters: Variables that control transitions (e.g. speed, isGrounded).

Using the Animator Component

  1. Add an Animator component to your GameObject.
  2. Assign the Animator Controller asset to the component's Controller slot.

State Transitions

In the Animator Window (Window -> Animation -> Animator):

  • Right-click a state and select Make Transition to draw a line to another state.
  • Add Conditions to the transition (e.g. if parameter speed > 0.1, transition from Idle to Run).
  • Has Exit Time: If checked, the transition waits for the current animation clip to finish before changing states. Uncheck this for instant responses (like jumping).

Triggering Transitions in Code

private Animator anim;

void Start()
{
    anim = GetComponent<Animator>();
}

void Update()
{
    float speedInput = Input.GetAxis("Horizontal");
    // Pass the speed input value to the animator parameter
    anim.SetFloat("Speed", Mathf.Abs(speedInput));

    if (Input.GetKeyDown(KeyCode.Space))
    {
        // Fire a trigger parameter
        anim.SetTrigger("Jump");
    }
}

TL;DR

  • The Animator component plays animation states.
  • The Animator Controller is a visual state machine window.
  • Parameters (Float, Int, Bool, Trigger) dictate when transitions fire.
  • Set variables in C# using anim.SetFloat() or anim.SetTrigger().