Animation is indispensable part for any game, this article demonstrates two ways to play animation in Unity.
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
.
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.
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);
}
}
Benefits: Fairly easy way to play animation. But we can't control how animation can be play except starting time.
Join the newsletter to receive the latest updates in your inbox.