I have a game object that has a health variable. When the health is <= 0 the enemy should play a death animation. However the animation I have for it to play isn’t playing. I’m basically following these docs (Unity - Scripting API: Animation.AddClip) though I’m using v18.3 (maybe that’s my issue? I couldn’t find newer examples of this). There is no error in the console and all my print()
statements are being hit.
I turned on Legacy mode for the animation as recommended in another post.
Edit: I should note the walking animation seems to momentarily stutter when the death animation should play.
My Code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
[SerializeField] float _health;
[SerializeField] AnimationClip _deathAnimationClip;
Animation anim;
float _currentSpeed = 0;
public void SetMovementSpeed(float speed) {
_currentSpeed = speed;
}
void Start() {
Animator anim = GetComponent<Animator>();
SetAnimations();
}
private void SetAnimations() {
// Set death animation
if (_deathAnimationClip != null) {
anim = GetComponent<Animation>();
anim.AddClip(_deathAnimationClip, "DeathAnimation");
}
else {
print("No death animation");
}
}
void Update()
{
transform.Translate(Vector2.left * _currentSpeed * Time.deltaTime);
}
public void takeDamage(float damage) {
_health -= damage;
if (_health <= 0) {
print("enemy is dead");
_currentSpeed = 0;
// TODO: Remove Rigibody so enemy can't still be hit
if (anim != null){
anim.Play("DeathAnimation");
}
else {
print("No death animation.");
}
// Destroy(gameObject);
}
}
}
Game Object
Animation Controller