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 /
avatar image
0
Question by fluxhackspro · Jun 15, 2018 at 10:39 PM · playerprefstimer

Save a timer in Hour:Minutes:Seconds to playerPrefs then load it on start

Hello getting a timer working it not difficult the difficult part is what value do i save? Im trying to save it to playerPrefs and when i start the game again it keeps on going on where it ended last time. So i wanna update it all the time and save it. And when i open it again i want to load the last values and keep on counting up.

Any help is welcome

~Flux

     public Text pastTimeText;
     float startTime;
 
     void Start ()
     {
         if (PlayerPrefs.GetFloat ("startTimer") == null) {
             startTime = Time.time;
             PlayerPrefs.SetFloat ("startTimer", startTime);
         } else {
             startTime = PlayerPrefs.GetFloat ("startTimer");
         }
     }
 
     private void Update()
     {
         //  Update countdown clock
         float t = Time.time - startTime;
         string hours = ((int)t / 3600).ToString ();
         string minutes = ((int)t / 60).ToString ();
         string seconds = (t % 60).ToString ("f2");
 
         PlayerPrefs.SetString ("timePassed", hours + ":" + minutes + ":" + seconds);
 
         pastTimeText.text = PlayerPrefs.GetString ("timePassed");
     }

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

2 Replies

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

Answer by trd99 · Jun 16, 2018 at 05:36 AM

Start by doing some googling for "c# TimeSpan" and "unity coroutines".

Do you need to calc the data on each update? ie every frame? If you can deal with slower updates look into using a coroutine to do the calculations say every 1/10 second. There is also a good asset for coroutines which I use on my projects in the store for free, not sure if I can name it here.

You also can move the writing of the data out to another event, such as OnApplicationQuit. If you do require writing more often or in the case of crashes, consider another coroutine.

Make an empty project. Copy this code into a c# class and add the usings (they didn't come across well here). Make an empty game object and drop this class into it. Make a ui canvas with a text box. Link the textbox into the code. Run it multiple times.

using System; using System.Collections; using UnityEngine; using UnityEngine.UI;

 public class NewBehaviourScript : MonoBehaviour
 {
     TimeSpan timeCounter;
     DateTime lastChecked;
 
     public Text txtTime;
     public float updateFrequency = 0.1f;
 
     // Use this for initialization
     void Start()
     {
         string strVal = PlayerPrefs.GetString ( "TimeRun" , "" );
         long ticks = 0;
 
         long.TryParse ( strVal , out ticks );
 
         timeCounter = new TimeSpan ( ticks );
 
         lastChecked = DateTime.Now;
 
         StartCoroutine ( CalcAndDisplay ( ) );
     }
 
     private void OnApplicationQuit()
     {
         PlayerPrefs.SetString ( "TimeRun" , timeCounter.Ticks.ToString ( ) );
         PlayerPrefs.Save ( );
     }
 
     IEnumerator CalcAndDisplay()
     {
         bool bRun = true;
 
         while ( bRun )
         {
             DateTime now = DateTime.Now;
 
             timeCounter += now - lastChecked;
 
             lastChecked = now;
 
             txtTime.text = "timePassed " +
                 string.Format ( "{0:D2}:{1:D2}:{2:D2}" , timeCounter.Hours , timeCounter.Minutes , timeCounter.Seconds );
 
             yield return new WaitForSeconds ( updateFrequency );
         }
     }
 }
 
Comment
Add comment · Show 2 · 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 fluxhackspro · Jun 16, 2018 at 07:57 AM 0
Share

This is a much more efficient counter, and i really appriciate that you took your time explaining it for me. Thanks a lot fam!

~Flux

avatar image trd99 fluxhackspro · Jun 17, 2018 at 10:18 PM 0
Share

no problem. i was guessing someone newer to c#, so a fullish example. irony of google is you need to know what to look for prior to finding answers...

do consider the free coroutine asset in the store. slightly different syntax, but less gc issues. it works well for my projects. i would leave it to you to stop the coroutine prior to killing the program.

best of luck

avatar image
0

Answer by smkgamespresent · Mar 07, 2020 at 04:59 AM

 using RTLTMPro;
     using UnityEngine;
     
     public class Clock : MonoBehaviour
     {
         float _time;
         private string _playTime;
         float _seconds, _minutes, _hours;
         public RTLTextMeshPro clockText;
     
         private void Awake()
         {
             _time = PlayerPrefs.GetFloat(Floppy.Clock);
         }
         private void Update()
         {
             _time += Time.deltaTime;
             SaveTime();
         }
     
         private void OnEnable()
         {
             clockText.text = GetClock();
         }
     
     
         public string GetClock()
         {
             _seconds = _time % 60;
     
             _minutes = _time / 60;
     
             _hours = _time / 3600;
             
             _playTime = $"{_hours:00} : {_minutes:00}  :  {_seconds:00}";
             
             return _playTime;
         }
     
         public void SaveTime()
         {
             PlayerPrefs.SetFloat(Floppy.Clock,_time);
         }
     }



Comment
Add comment · 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

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

91 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 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

Resetting Timer Using PlayerPrefs? (JS) 1 Answer

PlayerPrefs & Time.time 1 Answer

Not sure what is wrong with my timer script. 1 Answer

Time how long alive? 2 Answers

Save Time Button Settings in Player Prefs 2 Answers


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