Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice

Question Waiting for animations

Discussion in 'Animation' started by WizardHowell, Dec 17, 2023.

  1. WizardHowell


    Aug 11, 2023
    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.

    Code (CSharp):
    1. [SerializeField] GameObject dialogBox;
    3. public static bool isAnimatingDialog;
    5. void StartDialog()
    6. {
    7.     IEnumerator AnimateInAndStart()
    8.     {
    9.         isAnimatingDialog = true;
    10.         Animator animator = dialogBox.GetComponent<Animator>();
    11.         animator.SetTrigger("In");
    13.         yield return new WaitUntil(() => !isAnimatingDialog);
    15.         // do dialog start stuff
    16.     }
    17.     StartCoroutine(AnimateInAndStart());
    18. }
    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:

    Code (CSharp):
    1. public class DialogWatcher : MonoBehaviour
    2. {
    3.     public void SetAnimationEnded()
    4.     {
    5.       DialogManager.isAnimatingDialog = false;
    6.     }  
    7. }
    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.
  2. AcidArrow


    May 20, 2010
    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.