UrticaDioica UrticaDioica - 27 days ago 7
C# Question

Unity animations - yield return new WaitForSeconds(secs) not working

Why doesn't the animation play in Unity when I use this code? How could I make the program wait for the animation to end? In JavaScript (or UnityScript) this approach has worked.

public bool Attacking { get; set; }
private Animator anim;

void Start()
{
anim = gameObject.GetComponent<Animator>();
}

private IEnumerator Attack()
{
Attacking = true;

anim.SetTrigger("Attack"); // this is not playing

yield return new WaitForSeconds(attackLength);

Attacking = false;
}

Answer

This is how you run a Coroutine:

StartCoroutine(Attack());

or

StartCoroutine("Attack");

If you try to run it like a usual function it wont work.

So here is solution:

public void PlayAttack() 
{
    StartCoroutine(Attack());
}

Learn More