- Home /
Increase value through frames, or in a while?
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
}
Answer by NoseKills · Feb 13, 2017 at 07:14 AM
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.
Oooohhh that makes so much sense. What about in the case of a StartCoroutine that returns a flag, after a delay, for it to do stuff, would the first example still be better(easier to read/more efficient)?
I'd say that's very much just a judgement call that's very case specific.
Using Update like in the first example is probably the most performant solution, UNLESS you have a lot of objects, of which only a few need to run some logic every now and then. In that case removing the Update method alltogether and running said logic in a Coroutine might be better.
On the other hand, coroutines can be good for splitting up your code in more readable chunks.
In most cases the differences will be negligible, so just pick the solution that works for you and results in working code.
Better way to make a timer is InvokeRepeating("NameOfVoidToRepeat",0,10);
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
How can I make this code more efficient? 1 Answer
Distribute terrain in zones 3 Answers
Random NullReferenceException 0 Answers