How to handle delays with UI interaction, i.e. while playing an animation

This is an issue I have had multiple times when creating an UI. Let’s say I have a button that creates and destroys an instance of an object when toggled on or off. But there is an animation that scales the object from 0 to 1 to make it fade in, in a cool way rather then just popping up. The poblem is that this animation takes like 1 second, and if I toggle the button again before the animation has finished strange things can happen. Now this was just a simplified example but things like the destroy command does not fire has happened to me, so the object is still in the scene but the button is in the create state so pressing it again creates a new instance. Do you understand what I mean? There UI and the events in the scenes gets out of sync if the user is clicking to fast.

I tried using coroutines for the animation and that really made this a problem, in the end I hade to fix it by handleing the animation (usually some kind of Lerp), inside the the Update function with if-statements.

I also had an app with multiple modes, you started in Mode A and could press a button to go to Mode B and that also added a new button so now you cound either go back to Mode A or go forward to Mode C, and from Mode C you could go to Mode D or back one step to Mode B, but not two steps to Mode A (you had to go to Mode B first). And here I got similar problems with the animations when the user was to quick to press the new buttons before the ‘mode transistion animations’ had finished playing, and the scene ended up looking really strange because all the modes got mixed up all over the place.

When I say animation I’m mostly refering to coded Lerp animations, but even playing animation clips is of interest in this discussion.

So what I would like to know more about is this:

  1. How do you handle this “out of sync” problem between the scene and the UI?
  2. Is there a general good practice to adhere to?
  3. Is there something built into the Unity UI EventSystem I can use?
  4. How do you handle coroutines and UI interactions dependencies?

Please share your experience with creating fluent, dynamic and creative UI system with Unity :slight_smile:

Cheers!

Yep, there absolutely is. What you want to do is build a state machine pattern. This common programming pattern is designed to manage and handle data flows. It works particularly well for situations like these.

In your simple example at the beginning, there would be three possible states:

1.) Not Started
2.) Animating
3.) Finished

Now, if the button was pressed, you would only enter the Animating state if the current state is Not Started. That would prevent the issues described.

Read up on the pattern on wikipedia for more information.