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

How WaitForSeconds works in C# ?

Discussion in 'Scripting' started by amirghayes, Jun 8, 2011.

  1. amirghayes

    amirghayes

    Joined:
    Apr 8, 2011
    Posts:
    98
    would someone please tell me how to use WaitForSeconds in C# ?
    I tried to use it in different ways but nothing happens , no errors tho

    one of the example is

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5.  
    6.  
    7. public class EnemySpawn : MonoBehaviour
    8. {
    9.    public Transform enemy;
    10.     void Start()
    11.     {
    12.         Wait();
    13.         Instantiate(enemy);
    14.     }
    15.  
    16.     private IEnumerator Wait()
    17.     {
    18.         yield return new WaitForSeconds(10);
    19.     }
    20.  
    21. }
    22.  
    23.  
    another example

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5.  
    6.  
    7. public class EnemySpawn : MonoBehaviour
    8. {
    9.    public Transform enemy;
    10.     void Start()
    11.     {
    12.         new WaitForSecods(10);
    13.         Instantiate(enemy);
    14.     }
    15.  
    16. }
    17.  
    neither works

    would someone please tell me what I'm doing wrong ?
     
  2. appels

    appels

    Joined:
    Jun 25, 2010
    Posts:
    2,687
    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class NewBehaviourScript : MonoBehaviour {
    5.  
    6.     IEnumerator Start () {
    7.         Debug.Log("start waiting");
    8.         yield return new WaitForSeconds(2.0F);
    9.         Debug.Log("finished waiting");
    10.     }
    11. }
     
  3. appels

    appels

    Joined:
    Jun 25, 2010
    Posts:
    2,687
    or :

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class NewBehaviourScript : MonoBehaviour {
    5.    
    6.     public Transform cube;
    7.    
    8.     IEnumerator Start () {
    9.         yield return new WaitForSeconds(2.0F);
    10.         Transform tmp = (Transform) Instantiate(cube, new Vector3(0.0F, 0.0F, 0.0F), Quaternion.identity);
    11.         yield return new WaitForSeconds(2.0F);
    12.         Destroy(tmp.gameObject);
    13.     }
    14. }
     
  4. amirghayes

    amirghayes

    Joined:
    Apr 8, 2011
    Posts:
    98
    thank you very much for your answer
    it finally worked
    do you have time please to explain the difference of your code from the first code I mentioned ?
    does it have to be in start function ? or it can be anything ?
    was my mistake by putting the word private on it ?
    isn't IEnumerator some sort of functions ? that I can call it inside other functions like start and update ?

    sory for all those questions but I'm starting in C# and only know the basic stuff not the advanced ones
    I appreciate your help
     
  5. npsf3000

    npsf3000

    Joined:
    Sep 19, 2010
    Posts:
    3,830
  6. amirghayes

    amirghayes

    Joined:
    Apr 8, 2011
    Posts:
    98
    Thank u NPSF3000 for the links
    I already read them couple of times but I didn't understand it quiet well as I'm not very good on C# yet
    I know it is very easy on javascript but I spent alot of time to learn C# so I prefer to use C# , I even tried to make a javascipt just for yield statements cause of its simplicity there but then I didn't know how I'm supposed to call it from a C# or I didn't give it a serious try :)
     
  7. npsf3000

    npsf3000

    Joined:
    Sep 19, 2010
    Posts:
    3,830
    Stick with C#.

    The main thing I want to point out is StartCoroutine().
     
  8. appels

    appels

    Joined:
    Jun 25, 2010
    Posts:
    2,687
    Stick with C# is my advice also. Besides some Unity specific stuff which you can find in the docs, you'll be better off.
    The interface containing the yield should be of type Enumerator :

    Code (csharp):
    1.     void Start () {
    2.         StartCoroutine("Wait");
    3.     }
    4.    
    5.     private IEnumerator Wait() {
    6.         yield return new WaitForSeconds(2.0F);
    7.         Transform tmp = (Transform) Instantiate(cube, new Vector3(0.0F, 0.0F, 0.0F), Quaternion.identity);
    8.         yield return new WaitForSeconds(2.0F);
    9.         Destroy(tmp.gameObject);
    10.     }
     
  9. bigmisterb

    bigmisterb

    Joined:
    Nov 6, 2010
    Posts:
    4,221
    LOL.. age old discussion. Yield to me works easier in JS, but I am so used to both it isn't funny.

    If you have learned C#, stick with it, else maybe JS would be more to your liking.

    Code (csharp):
    1.  
    2.     function Start () {
    3.         StartCoroutine("Wait");
    4.     }
    5.    
    6.     function Wait() {
    7.         yield WaitForSeconds(2);
    8.         var tmp : Transform = Instantiate(cube, Vector3(0, 0, 0), Quaternion.identity).transform;
    9.         yield WaitForSeconds(2);
    10.         Destroy(tmp.gameObject);
    11.     }
    12.  
     
  10. amirghayes

    amirghayes

    Joined:
    Apr 8, 2011
    Posts:
    98
    Okey thank you all I think I got it now and I will stick to C# as well
    btw , is there a way to call a function on JS from C# ?
    in C# I just need to make a public static function in any script to be able to call that function from another script and I do that by just typing the name of the script followed by comma and the function name
    but I don't know how I supposed to call a JS function from another C# script , is that possible ?
     
  11. SkaredCreations

    SkaredCreations

    Joined:
    Sep 29, 2010
    Posts:
    296
    To interact with JS scripts from C# ones you need to move the JS into "Standard Assets" folder because it is one of the folders that are check first during compilation (read here).
     
    Last edited: Jun 8, 2011
  12. amirghayes

    amirghayes

    Joined:
    Apr 8, 2011
    Posts:
    98
    well I'm sorry I think I still didn't get it right

    it seems that all code inside update() is executing parralel to the WaitForSeconds
    what I want to do is that , in the start after the instantiation of the prefab I need to wait for 5 seconds then I change the animation and the rotation of it then I wanna wait for another 5 seconds before the code in the update start to work
    so I'v put all those in the start() function and called the couroutine from there
    then in the update() function I'v put the code to translate the prefab and make it auto move
    but that doesn't work this way , as it starts to move at the same moment it gets instantiated

    anyway here is the code if someone might like to help

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using System.Globalization;
    5.  
    6. public class EnemyAnimation : MonoBehaviour
    7. {
    8.     void Start()
    9.     {
    10.  
    11.         StartCoroutine("Delay");
    12.  
    13.     }
    14.     IEnumerator Delay()
    15.     {
    16.         animation.Play("idle");
    17.         animation["idle"].wrapMode = WrapMode.Loop;
    18.         yield return new WaitForSeconds(5f);
    19.  
    20.         Quaternion q = UnityEngine.Random.rotation;
    21.         transform.rotation = new Quaternion(transform.rotation.x,
    22.             q.y, transform.rotation.z, transform.rotation.w);
    23.  
    24.     }
    25.  
    26.  
    27.     void Update()
    28.     {
    29.        
    30.         animation.Play("walk");
    31.         animation.wrapMode = WrapMode.Loop;
    32.         transform.Translate(Vector3.forward * Time.deltaTime);
    33.  
    34.  
    35.     }
    36.    
    37.    
    38. }
    39.  
    40.  
    with this code it starts the walk animation and move around at the moment it gets instantiated
    the instantiation is in another script attached to the prefab

    if I comment the update function it works as I need but ofc it doesn't move

    so anyone would tell me what is wrong in my code please ?
    or another way to pause the execution better than the WaitForSeconds()?
     
  13. amirghayes

    amirghayes

    Joined:
    Apr 8, 2011
    Posts:
    98
    okey ty but what next ? how to call it from C# ? would u give a snippet for the calling code ?
    cause when I did that I still don't get it in VS intellisense
     
  14. appels

    appels

    Joined:
    Jun 25, 2010
    Posts:
    2,687
    use a boolean in the update function to enable/disable the movement
     
  15. amirghayes

    amirghayes

    Joined:
    Apr 8, 2011
    Posts:
    98
    yeah I finally decided to do what you said appels
    a little dissapointed tho that there is nothing easier on Unity engine to achieve that
    making it works only depends on the C# not unity specific function or mrethod that ease our work like OnTriggerEnter and alot of other cool methods
     
  16. sidev

    sidev

    Joined:
    Jun 6, 2011
    Posts:
    22
    hi amirghayes,

    Have you looked at CoroutineManager on the asset store? It eases what you want to do as far as pausing/resuming coroutines.

    sidev
     
  17. amirghayes

    amirghayes

    Joined:
    Apr 8, 2011
    Posts:
    98
    thank you sidev I'm gonna look up for it , hope it is free :)
    my concern is if using couroutine can suspend the Update() function from running till the couroutine finishes , that doesn't happen with me , may be cause I'm doing something wrong, but so far the update() function run its code even if the couroutine didn't finsh :(
     
  18. sidev

    sidev

    Joined:
    Jun 6, 2011
    Posts:
    22
    Yes,
    In order to do that you need to use the concept of CoUpdate() on top of Update(). Here is some code I make for punleto before:

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Punleto : MonoBehaviour {
    5.  
    6.     // Use this for initialization
    7.     void Start () {
    8.         StartCoroutine(CoUpdate()); //This is REALLY IMPORTANT
    9.     }
    10.    
    11.     // Update is called once per frame
    12.     void Update () {
    13.    
    14.     }
    15.    
    16.     //This is the best way to put non performance sensitive code. ALWAYS create a CoUpdate() !!! believe me.
    17.     //Note: Coroutine Manager will help you stop, pause, resume or even reset this coroutine at will! Go for it.
    18.     IEnumerator CoUpdate(){ //ALWAYS have a CoUpdate, you ll thank me later...
    19.         while (true){ //Not necessary if you are using the "loop" mode in Coroutine Manager
    20.            
    21.             /* do some of your code there */
    22.             //NOTE: this code will loop forever until you stop it based on a given condition.
    23.             print("doing some stuff...");
    24.             yield return StartCoroutine(WaitForXSeconds(3.0f));
    25.             print("now we are done waiting. Let s move on");
    26.            
    27.            
    28.             yield return 0; //Do not erase this without caution!
    29.         }
    30.     }
    31.    
    32.     IEnumerator WaitForXSeconds(float seconds){
    33.         print("starting");
    34.         yield return new WaitForSeconds(seconds);
    35.         print("done!");
    36.     }
    37. }
     
  19. amirghayes

    amirghayes

    Joined:
    Apr 8, 2011
    Posts:
    98
    thank you again sidev , I'm gonna try that
    I've put all the code inside the Update() function and used a variabe to store the time and I check it for a specific value during the game , when the" if " is true I do my code then reset the variable
    I know this may be not efficient and may result in problems later but I hope not
    if I find it gonna give me alot of trouples I'm gonna use the last code you provided , thank you again
     
  20. vishal_merkurgame

    vishal_merkurgame

    Joined:
    Nov 17, 2017
    Posts:
    2
  21. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,596
    Did you post the code you were expecting to paste there? That code will not halt the game for 10 seconds. Also, "stopping the game for 10 seconds" is something you would never want to do. You always want to maintain a decent frame rate - even if you are pausing or delaying certain sequences within your code.

    If, instead, the intention here was to create the enemy after a 10 second delay, then line 10 (the instantiate) needs to go after line 15 (the yield).
     
  22. TaleOf4Gamers

    TaleOf4Gamers

    Joined:
    Nov 15, 2013
    Posts:
    825
    Alternatively, Start can be an IEnumerator so the boilerplate code of creating the Wait method is useless as you can just make 'Start' an IEnumerator and use the WaitForSeconds within it.
    Either way, I do not see the point in bumping this thread anymore so i'm out ;)
     
    Doug_B likes this.
  23. N00MKRAD

    N00MKRAD

    Joined:
    Dec 31, 2013
    Posts:
    210
    Good job lmao, you just bumped a 7 year old thread.