I hacked together a pseudo YieldInstruction to wait for the current or specified state to complete.
using UnityEngine;
using System.Collections;
public static class WaitForState
{
/// <summary>
/// Wait until specified state, int "hash" state on optional "layer", has started and finished.
/// </summary>
public static Coroutine Execute(Animator animator, int stateHash, int layer = 0)
{
return animator.GetComponent<CharacterAnimator>().StartCoroutine(StartCoroutine(animator, stateHash, layer));
}
/// <summary>
/// Wait until specified state, string "stateName" on optional "layer", has started and finished.
/// </summary>
public static Coroutine Execute(Animator animator, string stateName, int layer = 0)
{
return Execute(animator, Animator.StringToHash(stateName), layer);
}
private static IEnumerator StartCoroutine(Animator animator, int stateHash, int layer)
{
//Wait for our state to start.
while (animator.GetCurrentAnimatorStateInfo(layer).shortNameHash != stateHash)
{
yield return null;
}
//Wait for our state to end.
while (animator.GetCurrentAnimatorStateInfo(layer).shortNameHash == stateHash)
{
yield return null;
}
}
}
Here is an example of how you might use it
void Update()
{
if(Input.GetButtonDown("Fire"))
{
StartCoroutine("Attack");
}
}
IEnumerator Attack()
{
animator.SetBool("Attack", true);
yield return WaitForState.Execute(animator, "AttackState");
animator.SetBool("Attack", false);
}
So what’s going on in our example?
We check to see if the fire button has been pressed and if it has, we start the Coroutine Attack().
In our Coroutine, we set the “Attack” parameter to true, trigging our transition into the “AttackState”. “yield return WaitForState.Execute(animator, “AttackState”)” will tell the Coroutine to continue when the state has ended.
The reason we provide a state name in Execute is because typically Mecanim doesn’t transition to a new state as soon as you set a parameter so we need to poll GetCurrentAnimatorStateInfo until our state has started, then we wait for it to end.