- Home /
Resume timer after application exit
Hi there, nooby question lol.
I'm writing a timer that counts down from X minutes.
Countdown function:
private void UpdateTime()
{
secondTillRefill -= Time.deltaTime;
if (secondTillRefill <= 0)
{
currentLives++;
secondTillRefill = interval.TotalSeconds;
}
}
Save the time the application exits - The game is for WP8 - does this work for that?
private void OnApplicationQuit()
{
PlayerPrefs.SetString("TimeOnExit", DateTime.Now.ToShortTimeString());
}
So when I resume I'm currently doing this in Awake:
if (PlayerPrefs.HasKey("TimeOnExit"))
{
var x = DateTime.Now - DateTime.Parse(PlayerPrefs.GetString("TimeOnExit"));
secondTillRefill = x.TotalSeconds;
PlayerPrefs.DeleteKey("TimeOnExit");
}
And it doesn't work, hence the question xD.
So yeah say I exit the game and the timer is on 1:30 (1 minute, 30 seconds)
I restart the game 30 seconds later, the timer should show 1:00 (1 minute, 0 seconds).
Anyone point out the flaw?
Cheers
Haha yeah you got it. Well the problem isn't solved. Seems OnApplicationQuit isn't actually being executed on the WP8 device, however that's now a different question. Convert your comment to an answer and I will +vote and accept :)
This might not be applicable if you have some special requirements but ... You could change the logic so you always just save the last time that a life was lost, and how many were left at that point. Then, whenever you start the application you could calculate :
1) seems I dropped down to 1 lives left 24 $$anonymous$$s ago.
2) recharging 1 life takes 5 $$anonymous$$s
3) now i should have 1 + (int)(24 / 5) = 5 lives and i have used (25 % 4) = 4 $$anonymous$$utes of the ongoing recharge period.
That way you wouldn't have to care about the status of the app/device.
Answer by NoseKills · Apr 17, 2014 at 07:01 AM
var x = DateTime.Now - DateTime.Parse(PlayerPrefs.GetString("TimeOnExit"));
If you just look at the order of the subtraction, you notice that x gets bigger the longer you wait, right ? If I'm looking at it right, var x becomes is the amount of seconds you had the app closed, so you should subtract that from the saved value.
Thank you! Late night/early mornings aren't my time to code it seems lol
Your answer
Follow this Question
Related Questions
How can I track how much time has passed since a game was turned off? 2 Answers
How to make a timer read to the .001 of a second 2 Answers
Check System Time and execute function 1 Answer
Minute Timer Issue 1 Answer
Timer running down too quickly 1 Answer