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

C# Coroutines....again

Discussion in 'Scripting' started by Johker, Nov 25, 2010.

  1. Johker

    Johker

    Joined:
    Jun 24, 2010
    Posts:
    24
    I am having trouble getting co-routines to work in a demo project and any help would really be appreciated.
    I have the following code all in the same script:

    Code (csharp):
    1.  
    2. private void Start()
    3. {
    4.     StartCoroutine(Wait(1.0f));
    5. }
    6.  
    Code (csharp):
    1.  
    2. // This gets called from a button in the OnGUI function.
    3. public void Test()
    4. {
    5.     StartCoroutine(Wait(1.0f));
    6. }
    7.  
    Code (csharp):
    1.  
    2. private IEnumerator Wait(float seconds)
    3. {
    4.     print(Time.time);
    5.     yield return new WaitForSeconds(seconds);
    6.     print(Time.time);
    7. }
    8.  
    The problem is that both print functions print the exact same time for either StartCoroutine call. It is as if the WaitForSeconds function doesn't even get called. Anyone have any insight on this?
     
  2. mightymao

    mightymao

    Joined:
    Oct 21, 2009
    Posts:
    108
    Well, I am not quite sure exactly what you meant. However, the Start event is called once just before the first Updater event is called. For example,

    Code (csharp):
    1.  
    2.  void Start ()
    3.   {
    4.     print("Calling from Start event");
    5.     StartCoroutine(Wait(1.0f));
    6.   }
    7.  
    8. /*
    9. [COLOR="#006400"]Result after the Start event:
    10.  
    11. Calling from Start event
    12. Time before wait = 0
    13. Time after wait = 1.002969[/COLOR]
    14. */
    15.  
    16.   if (GUI.Button(new Rect((Screen.width / 2) - 70, Screen.height - 120, 140, 70), "Test"))
    17.   {
    18.    
    19.     Test();
    20.   }
    21.  
    22. /*
    23. [COLOR="#006400"]About 12 seconds after a game started, I pressed a button to call the Test function and
    24. result after calling Test function:
    25.  
    26. Calling from Test
    27. Time before wait = 12.31229
    28. Time after wait = 13.31814[/COLOR]
    29. */
    30.   public void Test()
    31.   {
    32.     print("Calling from Test");
    33.     StartCoroutine(Wait(1.0f));
    34.   }
    35.  
    36.   private IEnumerator Wait(float seconds)
    37.   {
    38.     print("Time before wait = " + Time.time);
    39.     yield return new WaitForSeconds(seconds);
    40.     print("Time after wait = " + Time.time);
    41.  
    42.   }
    43.  
    As you can see, the Time after wait is about 1 second bigger than the Time before wait.