I need to disable object after its current animation (state in animator) is finished.
Why is it doesn't work?
if (myObject.GetComponent<Animator().GetCurrentAnimatorStateInfo(1).normalizedTime == 1) {
myObject.SetActive(false);
}
It's not a good idea to compare float
directly like normalizedTime == 1
. Just use <
or >=
. You can also use Mathf.Approximately
.
Anyways, when you start an animation, start a coroutine function that checks if that animation is done. This prevents wasting time in the Update function to check when animation is done. That coroutine function should have a paramter that checks for the name of the animation.
IEnumerator OnAnimationComplete(string name)
{
Animator anim = myObject.GetComponent<Animator>();
while (anim.GetCurrentAnimatorStateInfo(0).IsName(name) && anim.GetCurrentAnimatorStateInfo(0).normalizedTime < 1.0f)
{
//Wait every frame until animation has finished
yield return null;
}
Debug.Log("Animation has finished");
//Do something
}
Usage:
1.Start the animation.
2.Start the OnAnimationComplete coroutine: StartCoroutine(OnAnimationComplete("JumpAnim"));
There other ways to do this too such as using the AnimationEvent
event. Check out the provided link for examples about this.