UI Rotate within seconds and stop

While Kurt is a coroutine hater, and nothing over the years I’ve said has ever managed to dissuade him, I think they’re significantly better than traditional state machines. They ARE state machines afterall. The ability to easily chain linear sequencing without ridiculous amount of boilerplate code is divine. My entire game, from top to bottom starting from the main menu all the way to the game over is done with coroutines.

The problem with your solution right now is that your coroutines never actually finish, so of course it’s hard to keep track of their state. Here’s a solution that’s more streamlined:

   private const float duration = 1.0f;
   private const float rot1 = 0.0f;
   private const float rot2 = 90.0f;

   void Start()
   {
       StartCoroutine(Sequence());
   }

   public IEnumerator Sequence()
   {
       yield return StartCoroutine(Turn(rot1, rot2));
       yield return StartCoroutine(Open());
       yield return StartCoroutine(Turn(rot2, rot1));
       yield return StartCoroutine(Close());

       StartCoroutine(Sequence());
   }

   public IEnumerator Turn(float a, float b)
   {
       float time = 0f;

       while(time < duration)
       {
           time += Time.deltaTime;

           transform.rotation = Quaterion.Euler(0, 0, Mathf.Lerp(a, b, time / duration));
 
           yield return null;
       }
   }

   public IEnumerator Open()
   {
       yield return new WaitForSeconds(1);
   }

   public IEnumerator Close()
   {
       yield return new WaitForSeconds(1);
   }

I used parameters for your Turn, so you don’t need to copy and paste code, any time you find yourself doing that you should think to yourself “how can I not do this”. The entire “state machine” is now found within the Sequence coroutine, which runs all of the other sequences in turn. I assume your Open and Close will have more logic to them, so I left them as is, even though right now they’re kind of pointless.

2 Likes