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

Return yield new WaitForSeconds NOT Working?

Discussion in 'Scripting' started by Cooper37, Jul 25, 2016.

  1. Cooper37

    Cooper37

    Joined:
    Jul 21, 2012
    Posts:
    383
    Hi Unity Community! For some reason the yield return new WaitForSeconds() just refuse to work! Is there any reason why? My timeScale is 1 and there's nothing else affecting the time. Thanks for any help! :)

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class Delay : MonoBehaviour {
    6.     public float waitForSeconds = 5f;
    7.     void Start () {
    8.         StartCoroutine (MissionWait(waitForSeconds));
    9.         Mission();
    10.     }
    11.     IEnumerator MissionWait(float wait){ yield return new WaitForSeconds (wait); }
    12. }
    13.  
     
    Last edited: Jul 25, 2016
  2. PhenixEmporium

    PhenixEmporium

    Joined:
    Jul 24, 2016
    Posts:
    22
    Because it is a separate Coroutine, it's timing won't affect the other Coroutines. Either make "Mission()" an IEnumerator and put the WaitForSeconds at the start, or just call "Mission()" after the WaitForSeconds inside of the "MissionWait()" function as shown below.

    Code (csharp):
    1.  
    2. [*]   void Start () {
    3. [*]       StartCoroutine (MissionWait());
    4. [*]   }
    5. [*]   IEnumerator MissionWait(){
    6. [*]      yield return new WaitForSeconds (waitForSeconds);
    7. [*]      Mission();
    8. [*]   }
    9. [*]}
     
  3. Denscrivent

    Denscrivent

    Joined:
    Mar 3, 2014
    Posts:
    4
    Coroutine works as a thread. You should put the function Mission() inside the coroutine after waitforseconds like PhenixEmporium showed
     
  4. Cooper37

    Cooper37

    Joined:
    Jul 21, 2012
    Posts:
    383
    While this is kinda an inconvenience compared to Java's yield WaitForSeconds, I have to majorly change some things in my game, including how I'm going to organize code lol but at least it works! Thank you!
     
  5. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,181
    It's not Java! Not even close!

    What UnityScript (which is what you're thinking of) does when you write yield return inside a method, is to magically turn that method into an IEnumerator, and magically turn all calls to that method into a StartCorotuine call.

    In C#, you can get some of the same magic. If you declare your Start method as an IEnumerator, Unity will run it as a Corotuine. So you can do what you're doing like this:

    Code (csharp):
    1. IEnumerator Start() {
    2.     yield return new WaitForSeconds(waitForSeconds);
    3.     Mission();
    4. }