Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question How to pause for coroutine?

Discussion in 'Scripting' started by limon1323, Apr 4, 2023.

  1. limon1323

    limon1323

    Joined:
    Aug 16, 2021
    Posts:
    1
    I have a class that iterates over functions to move an object, I need to pause when colliding with an object and continue the coroutine from the same place when pressing the button.
    Code (CSharp):
    1. public class MainLoop
    2. {
    3.     GameObject mainTarget;
    4.     List<Function_> sequence_;
    5.     public bool infiniteLoop;
    6.     public bool end;
    7.     private float waitTime;
    8.     private int step;
    9.     public bool paused=false;
    10.  
    11.     public MainLoop(GameObject mainTarget, List<Function_> sequence_)
    12.     {
    13.         this.end = false;
    14.         this.mainTarget = mainTarget;
    15.         this.sequence_ = sequence_;
    16.         this.waitTime = 1.2f;//wait time between functions in sequence (list)
    17.     }
    18.     public IEnumerator Play()
    19.     {
    20.  
    21.         WaitForSeconds wait = new WaitForSeconds(waitTime);
    22.         this.end = false;
    23.         foreach (Function_ fun in this.sequence_)
    24.         {
    25.             fun.Func(this.mainTarget);
    26.  
    27.             if (!paused)
    28.             {
    29.                 yield return wait;
    30.             }
    31.         }
    32.         this.end = true;
    33.     }
    34.  
    35.  
    36. }
     
    Magiichan likes this.
  2. Magiichan

    Magiichan

    Joined:
    Jan 5, 2014
    Posts:
    403
    Code (CSharp):
    1. while (paused) {
    2.     yield return null;
    3. }
    Yield return null will reschedule the coroutine the next frame. (source)