- Home /
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");
}
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 );
}
}
}
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
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
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);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612164839im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
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