- Home /
Accuracy of timer issue please help
I am trying to stop my timer exactly at 5. Here is the script: float timer = 0.0f;
void Update(){
bool stopTimer = false;
if (!stopTimer)
timer += 1 * Time.deltaTime;
if (timer >= 5.0f){
stopTimer = true;
}
}
When it stops its always a little bit over 5..... it is unaccurate and i tried if (timer == 5.0f) but then it just misses it somehow and the timer keeps going. :(
btw ,,shouldnt this line: bool stopTimer = false; be outside from Update?
Answer by Joyrider · Aug 19, 2013 at 03:22 PM
You'll never be on 5 seconds exactly. Your timer depends on Time.deltatime, which is the time between two frames. and that time will vary according to your scene and current actions.
Detect when it goes over the 5 seconds, and if needed for display purposes, you can assign 5 seconds exactly once you go over.
if (timer >= 5.0f){
stopTimer = true;
timer = 5.0f;
}
Answer by robertbu · Aug 19, 2013 at 03:31 PM
You cannot stop it exactly at 5.0. The problem is that Time.deltaTime varies from frame to frame, and even if it did not, it is unlikely that the value would exactly divide into 5. So one frame the value is somewhat less than 5.0, and the next frame it is a bit over.
To better see what is going one, do add this line of code at line 6:
Debug.Log(timer+", "+Time.deltaTime);
If stopping at exactly 5 seconds is important there are a couple of other approaches, but it depends on why it is important. Using FixedUpdate() for the calculation is one approach, but I believe you can lose fixed update frames under load.
all are as acurate, but if you want to know if you'll get a 5 seconds sharp, I doubt it, but you can try. If a multiple of the fixedTimeStep gives you 5. But still, like robertbu said, no garanties.
First for FixedUpdate() to work, the fixedTime step must divide evenly into 5.0. By default it is set to 0.02, so the default value works. I would still do '>=' in the comparison. As for accuracy, if the app isn't under a heavy load, you should be very close...closer than Time.deltaTime. Unity will act as if everything is accurate. Unity takes actions in other places in an attempt to keep the fixedTime steps even, but there are situations they just cannot be fixed. For example a sudden heavy calculation in Update() would cause a fixedUpdate frame to be lost. I'd have to experiment to see how Unity deals with this kind of situation.
There are potential other ways to deal with this issue. If you describe the problem you are trying to solve, perhaps someone can give you a better solution.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to integrate timer into my C# script? 2 Answers
How to create a delay between spawning of tiles. 0 Answers
Timer doesn't count 0 Answers