So I know so far normally if I want something to happen, lets say after 10 seconds, I would do.
public float delay = 10;
private float timer = 0;
void Update () {
if (timer <= delay) {
timer += Time.deltaTime;
} else {
//Do things
timer = 0;
}
}
But I was wondering if it is better if you do it in its own loop?
public float delay = 10;
void Update () {
float timer = 0;
while (timer <= delay) {
timer += Time.deltaTime;
}
//Do things
}
In the first example, execution enters the Update method every time Unity runs Update, adds the time that was passed since last update and does something if it notices 10 seconds have passed when Update is runs. It should work as you want.
The latter example won’t do the same thing the first one does. Let’s say Time.deltaTime is 0.02 seconds. The loop in the latter code snippet will just increment “timer” by 0.02 as fast as a loop runs, until “timer” equals 10. So it’ll be just a normal loop that does 500 loops and exits. Whatever code you have after the loop runs as soon as the loop is finished, not after 10 seconds.
The latter code snippet will be stuck in the loop until it finishes, so if you increase the value of the delay, the loop might take a long time to finish and cause framerate issues, since no other part of your code can run as long as your Update method is running the loop.