Wait for animation to finish

Hi!

I have a script for a funfair game i’m working on, and I cant figure out how can let the animation fully finish before the user can press the same key again.

I hope someone can help me with this.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;

public class SafetyBar : MonoBehaviour
{
    public Animator animator;
    public bool IsClosed { get; private set; } = true;

    public Gondola gondola;
    public Arm arm;
    public Floor floor;
    public Text label;


    private float exectureActionTime = 0;
    private Action scheduledAction = null;
    private float lastAnimation = 0;
    void Start()
    {
        animator = GetComponent<Animator>();
    }

    void Update()
    {
        if (label != null)
            label.text = IsClosed ? "closed" : "open";

        if (Input.GetKeyDown(KeyCode.B))
        {
            if (!IsClosed || (!floor.IsDown && !arm.IsMoving() && !gondola.IsMoving()))
            {
                exectureActionTime = Time.time + UnityEngine.Random.Range(0.0f, 1.0f);
                scheduledAction = () =>
                {
                            IsClosed = !IsClosed;
                    lastAnimation = Time.time;

                    if (IsClosed)
                    {
                        animator.Play("BeugelOmlaag");
                    }
                    else
                    {
                        animator.Play("Beugel");

                    }
                };
            }
        }

        if (exectureActionTime != 0 && scheduledAction != null && Time.time > exectureActionTime)
        {
            scheduledAction();
            exectureActionTime = 0;
            scheduledAction = null;
        }
    }
}

Why not using an Animaton Event at the very last frame of the animation ?

When you trigger the animation you “lock” your GameObject, at the end of the animation the Animation Event unlock the object.

The Update() method should look like :

void Update()
{
       if (!locked)
       {
              if (Input.GetKey(KeyCode.Space))
              {
                     GetComponent<Animator>().SetTrigger("my-animation");
              }
       }
}

And the Animtion Event is :
175683-capture.png

Where the Unlock method is:

public void Unlock ()
{
        locked = false;
}

Hi @verschurengiovanni, you can use animation events for that.

Or you can manually create wait in a coroutine:

yield return new WaitForSeconds(anim.GetCurrentAnimatorStateInfo(0).length+anim.GetCurrentAnimatorStateInfo(0).normalizedTime);

I made a small package which you can use to wait for animations to start or finish inside coroutines. You can check it out here: GitHub - ComradeVanti/UnityWaitForAnim: A custom yield-instruction for Unity to wait for animations to finish