How to use while loop without crashing the game

I notice that if you use non-incremental condition like

var time = Time.time;
//waits for 10 sec or while user is not pressing any key
while (Time.time-time<10  !Input.anyKeyDown)  {
//codes
}

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

var time = Time.time;
while (Time.time-time<10  !Input.anyKeyDown)  {
//codes
yield WaitForSeconds (0);
}

I can also use this as an alternative to update function

var duration : float = 2;
var speed : float = 3.2;
var time = Time.time;
//move object forward for 2 sec
while (Time.time-time<duration) {
transform.Translate(Vector3.forward*speed*Time.deltaTime);
yield WaitForSeconds(0);
}

I’ts a bit hacky but helpful :smile:

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.

yeah thanks for the explanation :slight_smile:

Also don’t use “yield WaitForSeconds(0)”…if you want to wait a frame, just use “yield”.

–Eric

Thx guys. this happened to me also, and it was because i was putting “yield” outside the while loop. facepalm

2 Likes