- Home /
Error while using Time.deltaTime
This script freeze the editor and I can't figure out why
float previousTime = 0f;
void Update(){
while((Time.deltaTime - previousTime) < 1f)
Debug.Log("moving object");
}
Do you know what is Time.deltaTime
? It's the time needed to render the last frame.
Do you know what a while
loop does? It will loop, again, again and again, until the condition is false.
Do you know when a frame is rendered? After all the Update
methods on all the Behaviours are called (well, actually, it's more complicated than that)
Now, do you see your mistake? You don't allow a frame to be rendered because of your while
loop, and even if you did (using a simple if
ins$$anonymous$$d of a while
), the condition would be (hopefully for you) always true, since the time to render a frame should be less than a second.
Answer by tBurger · Jul 01, 2020 at 02:06 PM
As @Hellium correctly points out in their comment. You're while loop is running infinitely. Unfortunately Unity doesn't detect infinite while loops and just freezes.
So to clarify: Unity calls Update() once a frame. A While loop on the contrary has to finish during a single frame. If that doesn't happen, the frame is never completed, hence the freeze.
Would help to know what exactly you're trying to do with that code, too.
Answer by superjustin5000 · Jul 01, 2020 at 02:09 PM
Because of the nature of the while loop. previousTime is 0, delta time is almost always less than 1. so delta time - 0 IS less than 1. Your while loop will run continuously because none of those values are being allowed to change. If your while loop is runs infinitely, control will never return to the update function and you'll never leave the update function, so unity is basically stuck at your while loop.
Your answer
Follow this Question
Related Questions
Adding a ui text as a child of canvas disables all child buttons and makes them break 1 Answer
Animation load bug 0 Answers
Camera culling problem 3D 0 Answers
Blue glow around model 1 Answer
Toggle.isOn= var calls StackOverflowException+ Logs 1 Answer