You've successfully subscribed to Hacking with Unity - Learn how to create your own games
Great! Next, complete checkout for full access to Hacking with Unity - Learn how to create your own games
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

Unity: 2 ways to play animation

Ben Liu
Ben Liu

Animation is indispensable part for any game, this article demonstrates two ways to play animation in Unity.

Approach 1: use animation parameter

In the bellow example, there are three animations for the character, cucumber_idle, cucumber_walk and cucumber_die. Here we used a cucumber_die can be triggered by a parameter (on the left) called onDieAnimation.

Animator

So in the code , animation cucumber_die can be played by the following code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Enemy : MonoBehaviour {

    // Animation
    private Animator animator;

    private void Awake() {
        this.animator = GetComponent<Animator>();
    }

    private void Die() {
        // play onDieAnimation
        this.animator.SetTrigger("onDieAnimation");
        Destroy(this);
    }
}

Notice: this script must be attached a game object, and a condition/parameter must be created.

Benefits: It is more controllable as we can use the parameters to control the animation.

Approach 2: Use Animation Name

The other way to play an animation is to call its name.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Enemy : MonoBehaviour {

    
    // Animation
    private Animator animator;

    private void Awake() {
        this.animator = GetComponent<Animator>();
    }

    private void Die() {
        // play onDieAnimation
        this.animator.Play("cucumber_die", 0, 0.25f);
        Destroy(this);
    }
}
  • 1st parameter: animation name string.
  • ‌2nd parameter: animation layer, by default it is -1. You should use a proper value (depends on your project setting) here to make sure this animation can be played in the front. Otherwise it will be hidden.
  • 3rd parameter: start from animation's what time to play with. For example, if the whole animation is around 0.5 seconds, but you want to play this animation starts from the half, so in this case, you can put 0.25.

Benefits: Fairly easy way to play animation. But we can't control how animation can be play except starting time.

Ben Liu

Please feel free to contact me if you have any question. <br> https://t.me/NeedoneApp