- Home /
How would I make a timer frame independent?
I've recently had a problem with finding a way to make a timer frame independent. I've currently been using this:
public float timer = 0f;
void Update (){
if(timer < 250){
timer = timer + 1;
} else if (timer >= 250){
timer = 0f;
//Do stuff here
}
}
This has been working for me while using V-Sync, for then the code updates only 60 times in one second. However, some computer do not have as good of hardware, so the code then doesn't run at the ideal speed and it's all messed up.
I know to make it independent from frames, I should multiple it by Time.deltaTime, but I have no idea how where to do this. I've tried putting timer -= Time.deltaTime;
in the update function, however this did not help me.
Could IEnumerators with their yeild return new WaitForSeconds(TimeHere);
function work for this purpose, or is there a better way? Thanks!
Answer by ninjapretzel · Jun 20, 2015 at 02:40 AM
Don't need to use IEnumerators.
Time.deltaTime is easy to use.
It represents the fraction of a second elapsed over the last frame.
Just add it to timer, and when a second has elapsed it will be ~1.00, +/- a little bit based on the frame rate
If you want something happening every 4 seconds, you could do the following:
public float timer = 0;
public float timeout = 4;
void Update() {
timer += Time.deltaTime;
if (timer > timeout) {
timer -= timeout;
//Do stuff here
}
}