I'd like to use time.timescale = 0 to freeze the game, show an image, wait 3 seconds based on a timer, and then resume automatically using time.timescale = 1;
I think 'yield return new WaitForSeconds(3F);' doesn't work when time.timescale == 0. Am I wrong?
:)
Is there some other way, if I'm right with the above?
You're right, if you set the timescale to zero, the WaitForSeconds command won't work. For example, in the following code, the "WaitForSeconds" actually ends up taking 10 times as long as whatever duration is provided (as the variable 'p') to complete because of the timescale:
And with a timescale of 0.0, the WaitForSeconds never completes. The way around this is to time the duration yourself using the Time.realtimeSinceStartup property, which works independently of the timeScale. See the following example:
A simpler but effective way is just to use a really small value for timeScale. Unless you intend on waiting literally for thousands of years, it's just as good as 0.
The answers accepted at the time of writing this reply are from 2010. The Unity API has changed a lot since then, and now Time.unscaledDeltaTime is also available, which makes doing this a lot easier:
private IEnumerator PauseForSeconds (float pauseDuration) {
float originalTimeScale = Time.timeScale; // store original time scale in case it was not 1
Time.timeScale = 0; // pause
float t = 0;
while (t < pauseDuration) {
yield return null; // don't use WaitForSeconds() if Time.timeScale is 0!
t += Time.unscaledDeltaTime; // returns deltaTime without being multiplied by Time.timeScale
}
Time.timeScale = originalTimeScale; // restore time scale from before pause
}