Alright, so there’s plenty of information on how to do this with 3D animations, but I’m stumped with Unity 4 on how to do this in 2D. I have a very short animation, it’s close to a second long, what I want to do is have it play once, and then delete itself. I tried doing:
if (!animation.isPlaying) {
Destroy (gameObject);
}
However, this gives me an error saying there is not animation connected. The only other way is to calculate how long the animation is in total, and then set a timer to delete after it’s done, however that gives me little flexibility. What am I supposed to do, how would I achieve this?
public class DestroyOnExit : StateMachineBehaviour {
public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) {
Destroy(animator.gameObject, stateInfo.length);
}
}
Thus you schedule object deletion just when animation has finished.
Also account for stateInfo.speed or stateInfo.speedMultiplier
I create a script named “AnimationAutoDestroy”, and add this component to the animator game object which you want to auto-destroy while animation is finished. You can adjust the delay time as you want.
using UnityEngine;
using System.Collections;
public class AnimationAutoDestroy : MonoBehaviour {
public float delay = 0f;
// Use this for initialization
void Start () {
Destroy (gameObject, this.GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).length + delay);
}
}
Just a disclaimer. myAnimatorReferenceName.GetCurrentAnimatorStateInfo(0).length gets the SECONDS, so if you need the frames like I did just do length * 60f.
P.S - I’m using timers inside of state machines instead of IEnumerators.