Waiting for animations

Hey. I’m learning Unity and I’ve been working on a game with some animations that need to be waited, such as

  • Screen transitions, as in fade to black, do something (like change the position), fade the black out
  • Dialog transition, as in the panel flies in, typewriter effects starts, then panel flies out when the dialog is over (and until it flies out the player can’t start moving or whatever else)

So, pretty basic use cases, just wait for the animation to end. Not sure how to do that well though. Here is how I implemented it, using animation events.

[SerializeField] GameObject dialogBox;

public static bool isAnimatingDialog;

void StartDialog()
{
    IEnumerator AnimateInAndStart()
    { 
        isAnimatingDialog = true;
        Animator animator = dialogBox.GetComponent<Animator>();
        animator.SetTrigger("In");
       
        yield return new WaitUntil(() => !isAnimatingDialog);
       
        // do dialog start stuff
    }
    StartCoroutine(AnimateInAndStart());
}

Now as you see, the script handling the dialog is attacked to a parent of the dialogBox, which gets animated. Animation events as far as I know need the script to be on the same object. So what I did is put this script on the dialogBox:

public class DialogWatcher : MonoBehaviour
{
    public void SetAnimationEnded()
    {
      DialogManager.isAnimatingDialog = false;
    }  
}

And so obviously the fade in effect has an animation event that hooks into this method, and sets the static field on the other script.

Thing is I’m not very happy with this, but I don’t know what’s a better way to do animation → wait → do stuff in general.

So if anyone has suggestions/good resources on this, much appreciated.

This is not quite what you’re asking, but I would do fade ins / fade outs via script and then you have many options on how to trigger stuff when the fade is done.

In general, waiting for animations to end while sometimes is maybe unavoidable, it is the source of a lot of problems.