As it is said here :
Time.time
The time at the beginning of this frame (Read Only). This is the time in seconds since the start of the game.
And as I know the time is stored in float. So, my question is what will happen when the value of time becomes very large? Can it overflow? Will it lose precision and cause bugs? Will the game just crash or what?
Answer
There is a real risk to loss of time accuracy from using a single-precision float.
It will still retain accuracy to the nearest second for 97 days. But in games we often care about accuracy on the order of a frame duration.
A single-precision float time value in seconds starts to lose millisecond accuracy after about 9 hours.
That's already not outside the realm of possibility for a single play session, or leaving the game running "AFK" while you're at work/school or sleeping. (This is one reason why a common way to test a game is to run it overnight and check that it still plays correctly in the morning)
On modern consoles, where games are often suspended and resumed between play sessions rather than shut down entirely, it's not unexpected for a "single session" from the game's eye view to exceed 9 hours of runtime even when played in short bursts.
Assuming Unity's deltaTime
is computed from a higher-precision time source, which is borne out by Peter's experiments in another answer, relying on deltaTime
for frame-scale timings is relatively safe (just be cautious of accumulating very long durations by summing deltaTime
values - adding small increments to a larger float is a classic recipe for precision loss, even when you compensate with savvy algorithms).
Since fixedDeltaTime
keeps the same value you set, rather than dynamically changing from frame to frame, you can also put timing-sensitive behaviour in FixedUpdate to get stronger guarantees of consistency. deltaTime
will automatically return the appropriate fixed delta in these methods. While there can be a beat frequency between fixed & frame updates, you can smooth this out through interpolation.
What you want to avoid is computing durations by subtracting one timestamp from another. After hours of play this can cause catastrophic cancellation, leading to far less precision than you get early in the run. If comparing timestamps is important to your systems, you can generate your own higher-resolution time value using other methods, like System.Diagnostics.Stopwatch
instead of Time.time
.
No comments:
Post a Comment