0
0
Unityframework~5 mins

Animator controller for 2D in Unity

Choose your learning style9 modes available
Introduction

An Animator Controller helps you control how your 2D character moves and changes animations smoothly.

When you want your 2D character to walk, run, jump, or idle with smooth animation changes.
When you need to switch animations based on player input or game events.
When you want to blend between animations for natural movement.
When you want to organize multiple animations in one place for easy control.
Syntax
Unity
Animator Controller is created in Unity Editor as a visual graph.
You add animation states and connect them with transitions.
Use parameters (like bool, float) to control transitions.

You do not write code for the Animator Controller itself; it is made visually in Unity Editor.

Use scripts to change parameters that control animation transitions.

Examples
This example shows how to switch between Idle and Walk animations using a boolean parameter.
Unity
1. Create states: Idle, Walk, Jump
2. Add transitions: Idle -> Walk, Walk -> Idle
3. Add parameter: bool isWalking
4. Transition condition: isWalking == true for Idle -> Walk
Using a float parameter like speed allows smooth control based on movement speed.
Unity
1. Add float parameter: speed
2. Transition condition: speed > 0.1 for Idle -> Walk
3. Transition condition: speed <= 0.1 for Walk -> Idle
Sample Program

This script controls a 2D player. It reads horizontal input, moves the player, and sets the "speed" parameter in the Animator to switch animations.

Unity
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    private Animator animator;
    private float speed = 0f;

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

    void Update()
    {
        float move = Input.GetAxisRaw("Horizontal");
        speed = Mathf.Abs(move);
        animator.SetFloat("speed", speed);

        if (move != 0)
        {
            transform.Translate(move * Time.deltaTime * 5f, 0, 0);
            transform.localScale = new Vector3(Mathf.Sign(move), 1, 1);
        }
    }
}
OutputSuccess
Important Notes

Always add parameters in the Animator Controller that match the ones you set in code.

Use transitions with conditions to avoid sudden animation jumps.

Test animations in Play mode and adjust transition durations for smoothness.

Summary

Animator Controllers let you manage 2D animations visually in Unity.

Use parameters to control when animations change.

Scripts update these parameters based on player actions or game events.