Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
1
Question by Bakausagichan · Jul 26, 2016 at 11:01 PM · timerapplication.quit

Unity2D: How to resume timer even after application has quit

Basically I have a countdown timer with in my game. What I basically want to do is continue my timer playing even if I close out of my application and play it again, I want the timer to continue counting down. Kind of like clash of clan when the counter is still work when the app is closed. For example: if I exit the game and the timer is on 1:30 (1 minute, 30 seconds). Then if I restart the game 30 seconds later, the timer should show 1:00 (1 minute, 0 seconds) Or if I close the game 30 seconds later, the timer should show 1:00 (1 minute, 0 seconds)

So far this is as far as I've got:

 public Text timer;
 float minutes = 1;
 float seconds = 0;
 float miliseconds = 0;
 public int curHealth;
 public int maxHealth = 3;

 void Start ()
 {
     curHealth = maxHealth;
 }

 void Awake ()
 {

     if (PlayerPrefs.HasKey("TimeOnExit"))
     { 
         var x = DateTime.Now - DateTime.Parse(PlayerPrefs.GetString("TimeOnExit"));
         PlayerPrefs.DeleteKey("TimeOnExit");
     }
 
 }
 void Update(){
     if(miliseconds <= 0){
         if(seconds <= 0){
             minutes--;
             seconds = 59;
         }
         else if(seconds >= 0){
             seconds--;
         }
         
         miliseconds = 100;
     }
     
     miliseconds -= Time.deltaTime * 100;
     
     //Debug.Log(string.Format("{0}:{1}:{2}", minutes, seconds, (int)miliseconds));
     timer.text = string.Format("{0}:{1}", minutes, seconds, (int)miliseconds);
 }
 private void OnApplicationQuit()
 {
     PlayerPrefs.SetString("TimeOnExit", DateTime.Now.ToShortTimeString());
 }

}

But it doesn't really work as nothing really happens when I close the game and re-open it again as the timer just restarts.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
3
Best Answer

Answer by TBruce · Jul 27, 2016 at 12:50 AM

Try out this updated version of your script (tested)

 public Text timer;
 int minutes = 1;
 int seconds = 0;
 float miliseconds = 0;
 public int curHealth;
 public int maxHealth = 3;
 
 private int savedSeconds;
 
 void Start ()
 {
     curHealth = maxHealth;
 }
 
 void Awake ()
 {
     if (PlayerPrefs.HasKey("TimeOnExit"))
     { 
         miliseconds = PlayerPrefs.GetFloat("TimeOnExit");
 
         minutes = (int)miliseconds / 60;
         miliseconds -= (minutes * 60);
 
         seconds = (int)miliseconds;
         miliseconds -= seconds;
 
         PlayerPrefs.DeleteKey("TimeOnExit");
     }
 
 }
 
 public void Update()
 {
     // count down in seconds
     miliseconds += Time.deltaTime;
     if(miliseconds >= 1.0f)
     {
         miliseconds -= 1.0f;
         seconds--;
         if(seconds < 0)
         {
             seconds = 59;
             minutes--;
         }
     }
     
     if (seconds != savedSeconds)
     {
         //  Show current time
         timer.text = string.Format("Time : {0}:{1:D2}", minutes, seconds);
         savedSeconds = seconds;
     }
 }
 
 private void OnApplicationQuit()
 {
     miliseconds += ((minutes * 60) + seconds);
     PlayerPrefs.SetFloat("TimeOnExit", miliseconds);
 }
Comment
Add comment · Show 6 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Bakausagichan · Jul 27, 2016 at 08:30 AM 0
Share

It worked, Thank you soooooo much, you've been a big help!!!!! Just one problem, when the timer gets to 0:00 the timer continues going, when it hits 0:00 I the timer to restarts and countdown again and not go below 0:00.

avatar image TBruce Bakausagichan · Jul 27, 2016 at 04:48 PM 0
Share

Here is an updated version of my original answer.

 public Text timer;
 int $$anonymous$$utes = 1;
 int seconds = 0;
 float miliseconds = 0;
 
 public int curHealth;
 public int maxHealth = 3;
 
 [Range(1, 59)]
 public int defaultStart$$anonymous$$inutes = 1;
 public bool allowTimerRestart = false;
 
 private int savedSeconds;
 private bool resetTimer = false;
 
 void Start ()
 {
     curHealth = maxHealth;
 }
 
 void Awake ()
 {
     $$anonymous$$utes = defaultStart$$anonymous$$inutes;
     if (PlayerPrefs.Has$$anonymous$$ey("TimeOnExit"))
     { 
         miliseconds = PlayerPrefs.GetFloat("TimeOnExit");
 
         $$anonymous$$utes = (int)miliseconds / 60;
         miliseconds -= ($$anonymous$$utes * 60);
 
         seconds = (int)miliseconds;
         miliseconds -= seconds;
 
         PlayerPrefs.Delete$$anonymous$$ey("TimeOnExit");
     }
 
 }
 
 public void Update()
 {
     // count down in seconds
     miliseconds += Time.deltaTime;
     if (resetTimer)
     {
         ResetTime();
     }
     if (miliseconds >= 1.0f)
     {
         miliseconds -= 1.0f;
         if ((seconds > 0) || ($$anonymous$$utes > 0))
         {
             seconds--;
             if (seconds < 0)
             {
                 seconds = 59;
                 $$anonymous$$utes--;
             }
         }
         else
         {
             // add extra code here (may also need to add a flag so that this is not called continually)
             resetTimer = allowTimerRestart;
         }
     }
     
     if (seconds != savedSeconds)
     {
         //  Show current time
         timer.text = string.Format("Time : {0}:{1:D2}", $$anonymous$$utes, seconds);
         savedSeconds = seconds;
     }
 }
 
 void ResetTime()
 {
     $$anonymous$$utes = defaultStart$$anonymous$$inutes;
     seconds = 0;
     savedSeconds = 0;
     miliseconds = 1.0f - Time.deltaTime;
     resetTimer = false;
 }
 
 private void OnApplicationQuit()
 {
     int numSeconds = (($$anonymous$$utes * 60) + seconds);
     if (numSeconds > 0)
     {
         miliseconds += numSeconds;
         PlayerPrefs.SetFloat("TimeOnExit", miliseconds);
     }
 }

I added a couple of things.

  1. public int defaultStart$$anonymous$$inutes = 1; // set this to the default start time

  2. public bool allowTimerRestart = false; // set this to true if you want the timer to reset when it reaches 0

If the timer reaches 0:00 and allowTimerRestart is set to false the the timer will remain at 0:00 (you will need to add any extra coding when the timer reaches 0:00).

If the timer reaches 0:00 and allowTimerRestart is set to true the the timer will reset to defaultStart$$anonymous$$inutes on second later (you will need to add any extra coding when the timer reaches 0:00 before the timer resets).

avatar image Bakausagichan TBruce · Jul 27, 2016 at 10:22 PM 0
Share

That worked perfectly, Thank you sooo much!!! you've help me sooo much and I really appreciate. Thank you! Uh, sorry but would it be a but too much of a problem if you can help me with one last thing, you see I want to make the timer to continue going/ counting down when the application is closed. Is that possible? Thank you again

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

67 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Need help with making disappearing platforms. Error CS1525 1 Answer

My float is always adding 1f to it even with no code telling it to 1 Answer

PowerUp Timer 0 Answers

Timer issues when converting to minutes,hrs,days,months,years 0 Answers

How do I put a timer in RollerBall? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges