Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Attempting to StartCoroutine in a Coroutine crashes

Discussion in 'Editor & General Support' started by Emanuel, Mar 9, 2006.

  1. Emanuel

    Emanuel

    Joined:
    Feb 24, 2006
    Posts:
    11
    I am trying to start a coroutine inside of another coroutine. However, I find that StartCoroutine() crashes inside of any coroutine with a NullReferenceException. In the case of the C# code below, the StartCoroutine() call in Coroutine1() is the culprit.

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class NewBehaviourScript : MonoBehaviour {
    5.  
    6.     // Use this for initialization
    7.     void Start () {
    8.        StartCoroutine("Coroutine1");
    9.     }
    10.    
    11.     IEnumerator Coroutine1() {
    12.        StartCoroutine("Coroutine2");
    13.        yield return null;
    14.     }
    15.    
    16.     IEnumerator Coroutine2() {
    17.         Debug.Log("Coroutine2 started.");
    18.         yield return null;
    19.     }
    20. }
    21.  
    Is there another approach to achieving this behavior? I certainly could write a class that would be sure to flatten out the nested coroutines -- but the timing of the coroutines would be different then the ideal result from the above example.

    Also, related question -- Is there any way to make new YieldInstructions?
     
  2. Joachim_Ante

    Joachim_Ante

    Unity Technologies

    Joined:
    Mar 16, 2005
    Posts:
    5,203
    This bug has been fixed for 1.2.2. And is also in the recently released beta. You might want to check that out.


    You can chain coroutines which is basically the same.

    Code (csharp):
    1.  
    2. function DoSomething ()
    3. {
    4.    // Loop 5 times and wait one second every time.
    5.    for (var i=0;i<5;i++)
    6.    {  
    7.       yield WaitForSeconds (1.0)
    8.    }
    9. }
    10.  
    11. function Start ()
    12. {
    13.   yield StartCoroutine ("WaitForSomething");
    14.  
    15.   // Time.time will now be 5 seconds
    16.   print (Time.time);
    17. }
    18.