0
0
UnityHow-ToBeginner ยท 3 min read

How to Trigger Animation in Script in Unity Easily

To trigger an animation in Unity via script, use the Animator component and call methods like SetTrigger or Play on it. First, get a reference to the Animator in your script, then call animator.SetTrigger("TriggerName") to start the animation.
๐Ÿ“

Syntax

Use the Animator component to control animations in scripts. The main methods to trigger animations are:

  • SetTrigger(string triggerName): Activates a trigger parameter to start a transition.
  • Play(string stateName): Immediately plays the specified animation state.

Example syntax to trigger an animation:

Animator animator = GetComponent<Animator>();
animator.SetTrigger("Jump");
csharp
Animator animator = GetComponent<Animator>();
animator.SetTrigger("Jump");
๐Ÿ’ป

Example

This example shows how to trigger a "Jump" animation when the space key is pressed. It assumes you have an Animator component with a trigger parameter named "Jump" set up in your Animator Controller.

csharp
using UnityEngine;

public class AnimationTriggerExample : MonoBehaviour
{
    private Animator animator;

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

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            animator.SetTrigger("Jump");
        }
    }
}
Output
When you press the space bar, the "Jump" animation plays on the GameObject with this script and an Animator component.
โš ๏ธ

Common Pitfalls

  • Missing Animator component: Forgetting to add or assign the Animator component causes GetComponent<Animator>() to return null.
  • Wrong parameter name: The trigger name in SetTrigger must exactly match the parameter name in the Animator Controller.
  • Animator Controller setup: The animation transitions must use the trigger parameter to start the animation.
  • Not calling SetTrigger in Update or event: The trigger must be set in code at the right time, like in response to input or events.

Example of a common mistake and fix:

// Wrong trigger name
animator.SetTrigger("jump"); // "jump" != "Jump"

// Correct trigger name
animator.SetTrigger("Jump");
๐Ÿ“Š

Quick Reference

MethodDescription
SetTrigger(string)Starts an animation transition using a trigger parameter.
Play(string)Immediately plays the specified animation state.
ResetTrigger(string)Resets a trigger parameter to false.
GetComponent()Gets the Animator component attached to the GameObject.
โœ…

Key Takeaways

Use the Animator component and call SetTrigger with the exact trigger name to start animations.
Ensure the Animator Controller has the trigger parameter and transitions set up correctly.
Always get the Animator component reference before triggering animations in script.
Check for null Animator to avoid runtime errors if the component is missing.
Use Play to directly play an animation state without parameters if needed.