Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Help needed! Why is my coroutine not starting again?

Discussion in 'Scripting' started by flippedBrain, Jul 27, 2020.

  1. flippedBrain

    flippedBrain

    Joined:
    Aug 17, 2014
    Posts:
    56
    Hey there!

    I am trying to understand coroutines and I wonder why the coroutine "Test" can't be executed twice or more often in this simple script.

    My understanding of the following script is that the coroutine should stop and restart everytime I press the keycode H but it just runs the function Test() just once and ignores every further KeyCode H.

    Thanks for any hint.


    Code (CSharp):
    1.  
    2. public class Test : MonoBehaviour
    3. {
    4.    
    5.     IEnumerator loopTest;
    6.  
    7.     void Start()
    8.     {
    9.         loopTest = Test();
    10.     }
    11.     private void Update()
    12.     {
    13.         if(Input.GetKeyDown(KeyCode.H))
    14.         {
    15.             StopCoroutine(loopTest);
    16.             StartCoroutine(loopTest);
    17.         }
    18.     }
    19.  
    20.     IEnumerator Test()
    21.     {
    22.         for (int i = 1; i <= 10; i++)
    23.         {
    24.             Debug.Log("Loop: " + i);
    25.             yield return new WaitForSeconds(.5f);
    26.         }
    27.  
    28.         Debug.Log("Test loop finished!");
    29.     }
    30. }
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,011
    If you want to store a reference to a coroutine started on a monobehaviour, the StartCorotuine method returns a Coroutine so you could store the reference there.

    Code (CSharp):
    1. Coroutine loopTest;
    2.  
    3. private void Update()
    4. {
    5.     if (Input.GetKeyDown(KeyCode.H))
    6.     {
    7.         if (loopTest != null)
    8.             StopCoroutine(loopTest);
    9.  
    10.         loopTest = StartCoroutine(Test());
    11.     }
    12. }
     
    flippedBrain likes this.
  3. flippedBrain

    flippedBrain

    Joined:
    Aug 17, 2014
    Posts:
    56
    Thanks for your quick answer! It works like a charm now :)
    A null-reference check would have led me closer to an answer! Lesson learned.
     
unityunity