- Home /
Best practice for countdown timer on game resume
Hi all,
I'm creating a coroutine that counts down when the game is resumed from being paused (as seen in Temple Run, Subway Surfer, etc.) I have tried to use Time.realtimeSinceStartup as my timer to display the text after a brief delay, but its not working correctly.
On the first pause-resume cycle the text begins from 2 (instead of 3) then after a second or so 1, then it sets the timescale to 1 as it should. On subsequent cycles, no text is displayed at all, but it is entering the PlayCountdownTimer coroutine as I've checked this. I'm not sure what the problem is so was wondering if anyone can lend a hand with how to get it working. I should also mention that I'm using EZGUI and the SpriteText script for the text.
Also, I'd also be very interested in finding out what the best practice is for this kind of routine. I've seen suggestions of setting timescale to a very small number so that the WaitForSeconds yield instruction can be used, but I'm not too sure how to go about it this way.
Thanks
void OnPauseGame()
{
if (Time.timeScale == 1)
{
Time.timeScale = 0;
}
else
{
StartCoroutine(PlayCountdownTimer(4));
Time.timeScale = 1;
}
}
IEnumerator PlayCountdownTimer(int pauseDelay)
{
float pauseEndTime = Time.realtimeSinceStartup + pauseDelay;
while (Time.realtimeSinceStartup < pauseEndTime)
{
if (Time.realtimeSinceStartup > 0.5f && Time.realtimeSinceStartup <= 1)
// Display 3
ResumeGameSpriteTextScript_ref.Text = "3";
else if (Time.realtimeSinceStartup > 2 && Time.realtimeSinceStartup <= 3)
// Display 2
ResumeGameSpriteTextScript_ref.Text = "2";
else if (Time.realtimeSinceStartup > 3 && Time.realtimeSinceStartup <= 4)
// Display 2
ResumeGameSpriteTextScript_ref.Text = "1";
else
ResumeGameSpriteTextScript_ref.Text = "";
yield return null;
}
}
Answer by Gurc · Apr 04, 2013 at 05:25 PM
Why do you compare time to a constant? "Time.realtimeSinceStartup > 0.5f"
You should store time in OnPauseGame() like:
float time_started; OnPauseGame() { time_started=Time.realtimeSinceStartup; }
and check the time in coroutine like: if(Time.realtimeSinceStartup > 0.5f+time_started)
I am not so sure for below part: You should "yield return StartCoroutine() " for waiting of execution of countdown menu.
One more thing. What does your code show between seconds "1 and 2" which is not included in if/else conditions?
Your answer
![](https://koobas.hobune.stream/wayback/20220613095646im_/https://answers.unity.com/themes/thub/images/avi.jpg)