Mecanim 'Wait for animation to complete" functionality

I have a series of events that happen in my game using Coroutines. All of them work as expected except the “PlayOnce” helper function I’ve made that relies on the current animation state to provide it’s normalized time (should be between 0.0 and 1.0, where 0 is the beginning and 1 is the end of the animation.) The idea is to yield until the animation is completed, then the sequence can continue. It pulls an animator’s boolean high long enough to get the animation to start playing, then should play the animation to completion and pull the boolean low again.

If I change the condition from 0.95f to 0.095f, most animation work, but some jitter as the loop repeats infinitely. At 0.95f, all animations jitter infinitely. Here’s the code …

public IEnumerator PlayOnce(Animator changedAnimator, string paramName)
{
	changedAnimator.SetBool(paramName, true);
	yield return null;
	while (PlayerController.currentAnimator.GetCurrentAnimatorStateInfo(0).normalizedTime < 0.95f)
	{
		yield return null;
	}
	changedAnimator.SetBool(paramName, false);
}

Debug output of the normalizedTime value suggests that it makes it to ~0.01 - ~0.02 for most of the animations before it starts repeating constantly. And none of these animations are set to loop. And I’m not changing the normalized time anywhere. Simply checking it.

Thanks!

Experimentation proved useful here, as I was able to simply move line 9 (setting the boolean to false) above the while loop and now it works 100%. New code is:

public IEnumerator PlayOnce(Animator changedAnimator, string paramName)
{
    changedAnimator.SetBool(paramName, true);
    yield return null;
    changedAnimator.SetBool(paramName, false);
    while (PlayerController.currentAnimator.GetCurrentAnimatorStateInfo(0).normalizedTime < 0.95f)
    {
        yield return null;
    }
}

Hope it helps someone.

I believe in the latter case the while loop is probably unnecessary, you’re turning your boolean on and then flipping it back off on the next call.

This should cause the animation to play until completion once.

While that is true, this function serves more purpose than just playing the animation all the way through. As I stated, I’m using it in a series of Coroutines, so they fire off one after the other. An event happens after the animation is completed as opposed to right after firing off the animation.