- Home /
Moving a GameObject freezes Unity (Possible Infinite Loop)
private var savedTime = Time.time;
function awake () { savedTime = Time.time; }
function Update () {
print("Time: "+Time.time + " Saved Time: "+savedTime); while(Time.time - savedTime <= 5) { transform.Translate(Vector3.forward Time.deltaTime -10); } while (Time.time - savedTime >= 5 ) { transform.Translate(Vector3.forward Time.deltaTime -10); } while (Time.time - savedTime > 10) {
savedTime = Time.time;
} }
I don't get it, does Unity not use while loops, or am I using them wrong?
Answer by Eric5h5 · Nov 22, 2010 at 01:36 AM
All of your while loops are infinite loops. They will run forever since there is no possibility for the exit condition to be true. You have to wait until the next frame for Time.time to increase, but since the loop never exits, the next frame will never happen.
What you're trying to do is not suitable for Update, which runs once every frame and can't be delayed or interrupted. To schedule a series of events, use coroutines instead. Not sure what you're trying to do, but something like this:
function Start () { while (true) { yield Move(-10.0, 5.0); yield Move(10.0, 5.0); } }
function Move (speed : float, time : float) { for (i = 0.0; i < time; i += Time.deltaTime) { transform.Translate(Vector3.forward Time.deltaTime speed); yield; } }
Could you explain this further?
I checked out: http://unity3d.com/support/documentation/ScriptReference/Coroutine.html
But it doesn't make sense to much. Is their anything else I should really check out, or should I just go off of that?
@Justin Warner: also read all the linked pages about Yield. Anyway I added an example.
Answer by devilkkw · Nov 22, 2010 at 12:41 AM
while(Time.time - savedTime <= 5) and
while (Time.time - savedTime >= 5 )
is not correct,because u have 2 possibili =5 and make error.
try
while(Time.time - savedTime < 5) and
while (Time.time - savedTime >= 5 )
or
while(Time.time - savedTime <= 5) and
while (Time.time - savedTime > 5 )
$$anonymous$$ade sense to me, but no, still freezes up and I have to end it with task manager.
This happened before too with another loop...
Your answer

Follow this Question
Related Questions
How to make this kind of control ? 2 Answers
Check if a set of objects is moving 2 Answers
Moving a specific gameobject in a list 1 Answer
GameObject moving different in a build than normally 2 Answers