Search Unity

How to use while loop without crashing the game

Discussion in 'Scripting' started by VillainT_, Nov 27, 2012.

Thread Status:
Not open for further replies.
  1. VillainT_

    VillainT_

    Joined:
    Oct 31, 2012
    Posts:
    4
    I notice that if you use non-incremental condition like

    Code (csharp):
    1.  
    2. var time = Time.time;
    3. //waits for 10 sec or while user is not pressing any key
    4. while (Time.time-time<10  !Input.anyKeyDown)  {
    5. //codes
    6. }
    7.  
    in while loops most of time it end up crashing or hanging up unity
    I don'y know why but here's what I discover on using the while loop

    You can use
    Code (csharp):
    1.  
    2. var time = Time.time;
    3. while (Time.time-time<10  !Input.anyKeyDown)  {
    4. //codes
    5. yield WaitForSeconds (0);
    6. }
    I can also use this as an alternative to update function

    Code (csharp):
    1.  
    2. var duration : float = 2;
    3. var speed : float = 3.2;
    4. var time = Time.time;
    5. //move object forward for 2 sec
    6. while (Time.time-time<duration) {
    7. transform.Translate(Vector3.forward*speed*Time.deltaTime);
    8. yield WaitForSeconds(0);
    9. }
    10.  
    I'ts a bit hacky but helpful :D
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,537
    ...

    you don't have any idea what you're doing, do you?

    your first block of code is blocking (doesn't return), this is why unity hangs

    your second block of code is an implicit coroutine, this is why it doesn't block (yield is a return statement, but it's an iterating return)

    the same goes for your 3rd block of code.

    But in your 3rd block of code you're not waiting for any nominal amount of time. Causing your 'psuedo-update' to update VERY frequently... this would cause your 'Translate' call there to get called very frequently... and cause everything to act very fast.
     
  3. VillainT_

    VillainT_

    Joined:
    Oct 31, 2012
    Posts:
    4
    yeah thanks for the explanation :)
     
    Last edited: Nov 27, 2012
  4. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Also don't use "yield WaitForSeconds(0)"...if you want to wait a frame, just use "yield".

    --Eric
     
  5. FuzzyQuills

    FuzzyQuills

    Joined:
    Jun 8, 2013
    Posts:
    2,871
    Thx guys. this happened to me also, and it was because i was putting "yield" outside the while loop. *facepalm*
     
    Thalon4 and GTXGamedev like this.
Thread Status:
Not open for further replies.