Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Help needed! Why is my coroutine not starting again?

Discussion in 'Scripting' started by wm-VR, Jul 27, 2020.

  1. wm-VR

    wm-VR

    Joined:
    Aug 17, 2014
    Posts:
    123
    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,035
    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. }
     
    unity_yl5jbq0YuC3dxA and wm-VR like this.
  3. wm-VR

    wm-VR

    Joined:
    Aug 17, 2014
    Posts:
    123
    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.
     
    unity_yl5jbq0YuC3dxA likes this.