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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

WaitForSeconds problem

Discussion in 'Scripting' started by Onithec4t, Aug 2, 2014.

  1. Onithec4t

    Onithec4t

    Joined:
    Aug 2, 2014
    Posts:
    7
    Hi guys.
    I started learning unity using C# yesterday, but I know something about programming (with java).

    To learn, I'm trying to develop a simple pong game, but I've some trouble with WaitForSeconds.
    I think it can be related to the multithread engine.
    That's what i'm doing :

    Code (CSharp):
    1.  
    2. public class BallControl : MonoBehaviour {
    3.  
    4.     bool wait=false;
    5.    
    6.     void Start (){
    7.         if (!wait) {
    8.             Debug.Log(wait);
    9.             StartCoroutine(hi (5.0f));
    10.             Debug.Log(wait);
    11.         }
    12.         move ();
    13.     }
    14.  
    15.     IEnumerator hi(float sec){
    16.         Debug.Log("wait for "+sec+" seconds");
    17.         yield return new WaitForSeconds(sec);
    18.         Debug.Log("waited for "+sec+" seconds");
    19.         wait = true;
    20.         }
    21.     void move(){...}
    22. }

    When I start the game, the ball does not wait, but the console log is this:

    false
    false
    wait for 5 seconds
    waited for 5 seconds

    The hi method is called but it seems to be a separated thread.
    Any suggestions?
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    Coroutines are there to do exactly this, start something in a separate thread... what are you trying to achieve with this code?
     
  3. Onithec4t

    Onithec4t

    Joined:
    Aug 2, 2014
    Posts:
    7
    The ball should wait and after that, moves.
     
    Last edited: Aug 2, 2014
  4. der_r

    der_r

    Joined:
    Mar 30, 2014
    Posts:
    259
    Put the call to move() into your coroutine at the very end.
     
    Onithec4t likes this.
  5. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
    Coroutines are executed in the main thread. They are not multithreaded at all.

    der_r just gave you the correct hint. move() has to be in the coroutine, immediately after the waiting. I don't know exactly what the wait flag is supposed to do. As far as I can see it is not needed at all, but maybe you wanted it to do something else.
     
  6. Onithec4t

    Onithec4t

    Joined:
    Aug 2, 2014
    Posts:
    7
    the der_r solution works well, ty.
    The wait flag was just for debugging, not other uses.