Unity. How to pause script execution until animation ends?

Viewed 98

How to make the animation play and then the object changed coordinates, now the opposite is happening ?

     _animator.Play("Animation");
      WaitForAnimation(_animator);
    transform.position = StartPoint;
    dest = transform.position;
    Vector2 dir = Vector2.zero;
    _animator.SetFloat("DirX", 1);
    _animator.SetFloat("DirY", 0);


private IEnumerator WaitForAnimation(Animator animation)
{
    do
    {
        yield return null;
    } while (animation.GetCurrentAnimatorStateInfo(0).IsName("Animation"));
}
1 Answers

When you call a WaitForSeconds function (or freeze the time, which is what you do) inside the IEnumerator funciton, time will only freeze inside itself. More info here.

You should do something like:

    private IEnumerator WaitForAnimation(Animator animation) 
    {
         while (animation.GetCurrentAnimatorStateInfo(0).IsName("Animation"))
        {
           yield return null;
        }


         transform.position = StartPoint;
         dest = transform.position;
         Vector2 dir = Vector2.zero;
        _animator.SetFloat("DirX", 1);
        _animator.SetFloat("DirY", 0);
    }

Just a side note if the while (animation.GetCurrentAnimatorStateInfo(0).IsName("Animation")) doesn't work. I suggest calling a WaitForSecondsRealTime(time). You could hardcode the time or look at this.

Related