- Home /
Unity crashing when function runs
this function is being used to make sure an object waits for a certian number of seconds before it changes position, for some reason whenever this code is run unity crashes ? any ideas why ?
function wait(waittime : int){
waittime = 0.000;
var initialtime = Time.time;
var finaltime = 0.000;
var deltatime = waittime - 1.000;
while(deltatime<waittime){
finaltime = Time.time;
deltatime = finaltime - initialtime;
}
}
Good advice for beginners is to avoid while loops altogether.
On the other hand that tends to be bad advice for intermediate to advanced users.
Answer by rutter · Aug 08, 2014 at 06:36 PM
You've created an infinite loop.
Most game engines, including Unity, work something like this:
Advance the game state by one frame
Render game to screen
Rinse and repeat 30-60 times per second
Your scripts are useful in step one. Unity hands you control of the main thread, which is very powerful but also a bit risky if you do something that causes a crash.
Usually, each script should perform some small, quick operations in Update
. Anything that involves waiting is usually structured as a coroutine or timer check -- after all, the game needs to keep running, even if your script is waiting!
For example, you could check: is this script suppose to start moving, yet? Okay, then we do nothing during this frame. That's fine. You don't have to make every script do something in every frame.
In your case, you're looping based on Time.time
, which is bad for two reasons:
A wait on the main thread will hang your game until it's finished, which is bad.
Because
Time.time
updates only once per frame, your loop will actually never finish, which is why you're getting a crash.
Your answer
Follow this Question
Related Questions
Time Function in Javascript? 1 Answer
A node in a childnode? 1 Answer
Breathing sound effect using timers 1 Answer
Timer running down too quickly 1 Answer
Weird gameplay slow down problem 1 Answer