0
0
Unityframework~5 mins

2D animation basics in Unity

Choose your learning style9 modes available
Introduction

2D animation makes characters and objects move in games. It brings your game world to life and makes it fun to watch.

When you want a character to walk or jump in a 2D game.
To show effects like explosions or magic spells.
When you want buttons or menus to have smooth transitions.
To animate background elements like clouds or water.
When creating cutscenes or story moments with moving images.
Syntax
Unity
Animator animator = GetComponent<Animator>();
animator.Play("AnimationName");
Use the Animator component to control 2D animations in Unity.
Animations are created and managed in the Animator window using animation clips.
Examples
Play the 'Idle' animation clip on the object.
Unity
Animator animator = GetComponent<Animator>();
animator.Play("Idle");
Set a boolean parameter to control animation transitions.
Unity
animator.SetBool("isRunning", true);
Trigger a one-time animation like a jump.
Unity
animator.SetTrigger("Jump");
Sample Program

This script controls a 2D character's animations. Pressing space triggers a jump animation. Holding the right arrow key plays the running animation. Otherwise, the character stays idle.

Unity
using UnityEngine;

public class Simple2DAnimation : MonoBehaviour
{
    private Animator animator;

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

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            animator.SetTrigger("Jump");
        }
        else if (Input.GetKey(KeyCode.RightArrow))
        {
            animator.SetBool("isRunning", true);
        }
        else
        {
            animator.SetBool("isRunning", false);
        }
    }
}
OutputSuccess
Important Notes

Make sure your GameObject has an Animator component with animation clips set up.

Use parameters in the Animator to switch between animations smoothly.

Test animations in Play mode and use the Animator window to debug transitions.

Summary

2D animation in Unity uses the Animator component to play animation clips.

Control animations by setting parameters like bools and triggers.

Animations make your game characters and objects feel alive and interactive.