Search Unity

why does this make unity stop working?

Discussion in 'Scripting' started by ozgurdugmeci, Aug 27, 2015.

  1. ozgurdugmeci

    ozgurdugmeci

    Joined:
    Mar 1, 2015
    Posts:
    85
    i want to make unity count for 2 seconds.
    but couldnt make it done.



    Code (JavaScript):
    1. var timer : double;
    2. var i : int;
    3. function xxx()
    4. {
    5.    
    6.     timer = Time.time +2.0;
    7.     while(Timer.time<timer)
    8.     {
    9.       i=i+1;  
    10.     }
    11. }
    12.  
     
  2. gcoope

    gcoope

    Joined:
    Dec 20, 2012
    Posts:
    11
    That will loop infinitely, Time.time is always going to be less than Time.time + 2. You'll want to put a check in - probably an if, or use a Do() While() instead of just a while - to check when your timer is >= 2
     
  3. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    974
    Time.time returns the game time that has passed at the beginning of the frame. Within any kind of for, while or do loop it will remain constant. You need frames to pass before it changes.

    Either do your looping in a coroutine with a yield return delay, or make use of the fact that Update is called once per frame.

    Code (csharp):
    1. float nextTime = 2f;
    2. void Update()
    3. {
    4.   if (Time.time >= nextTime)
    5.   {
    6.     // do something
    7.     nextTime = Time.time + 2f;
    8.   }
    9. }
     
  4. ozgurdugmeci

    ozgurdugmeci

    Joined:
    Mar 1, 2015
    Posts:
    85
    my intention is to make a pause during the game for 2 seconds.
     
  5. AlanMattano

    AlanMattano

    Joined:
    Aug 22, 2013
    Posts:
    1,501
  6. ozgurdugmeci

    ozgurdugmeci

    Joined:
    Mar 1, 2015
    Posts:
    85
    thank you guys..
     
  7. ozgurdugmeci

    ozgurdugmeci

    Joined:
    Mar 1, 2015
    Posts:
    85
    i used yield WaitForSeconds(x),
    finally pain has gone away.
    thanks again
     
    Kurt-Dekker likes this.