Time.unscaledDeltaTime keeps increasing when app is in background

I am using 2019.4. Recently found a timing issue, I want to use Time.unscaledDeltaTime for counting time that not affect by Time.timeScale, and not count the time when app stays in background. Because it cares time only when game is playing.
For example, after starting the game in on mobile, then at any time enter to background, wait for 10 seconds. then bring the game back, in the 1st frame when the game comes back, Time.unscaledDeltaTime is 10 seconds. But I expect it as the time bewteen last frame and current frame in game time.
Is it expected behaviour or a bug? Although in the documentation it kind of correct, “The timeScale-independent interval in seconds from the last frame to the current one”
If it is expected, then is there any API to get unscaled delta time in game time?

You probably want to use Unity - Scripting API: MonoBehaviour.OnApplicationFocus(bool) and/or other related callbacks to detect when the game enters the background/re-enters the foreground and make adjustments as needed (for example ignoring the frame times for the first frame upon reopening the app)

1 Like

I encountered this problem today. Time.unscaledDeltaTime does count background time. But it isn’t affected by system clock settings. You can change the clock time without affecting its value.

Maybe we can use Time.deltaTime/Time.timeScale as a workaround.

You have the wrong idea about what deltaTime actually represents. It isn’t measured in “game time”. It’s the other way round. deltaTime is the time that passed between the last frame and the current. However unlike the unscaled version the normal deltaTime is affected by the timescale (which effectively slows down / speeds up the virtual ingame time) and also clamped to the max timestep. The max timestep is usually set to 0.33333. So even when a frame takes longer than 0.33 seconds, deltaTime would only report 0.3333.

So when the application is in the background, the real world time is just rolling on and when you come back after 10 seconds, well, 10 seconds have passed. deltaTime would be clamped to 0.333, the unscaled version is not. So the most simplest solution is to clamp it yourself

float uDT = Mathf.Min(Time.unscaledDeltaTime, 0.33333f);

Yes, time is not only measured with the system time or real time clock of a system. There are many high precision timers in a system (sometimes as part of the CPU itself, like the rdtsc). The system clock is almost never used for precise time measurements as the precision may be in the 10s of milliseconds or worse.

1 Like