- Home /
How to get a time to persist across objects that activate and deactivate?
I'm trying to keep accelerated time in a TMP_Text text box. I want to multiply my real time by 8. The printed timespan t is always correct, but the timerText lags behind to the last time it was active (it doesn't keep time in the background when it is .SetActive(false) - how do I do this correctly? The Update() code is outside of the TMP_Text GameObject, it's in a Singleton. Any help would be very much appreciated!
private float timer;
private float gameTime;
public TMP_Text timerText;
void Update()
{
timer = Time.realtimeSinceStartup;
print("Real time since startup" + timer);
gameTime = timer * 8;
print("Game Time = " + gameTime);
System.TimeSpan t = System.TimeSpan.FromSeconds(gameTime);
print("time span = " + t);
timerText.text = string.Format("{0:D2}:{1:D2}:{2:D2}", t.Hours, t.Minutes, t.Seconds, t.Milliseconds);
}
Answer by sacredgeometry · Mar 29, 2020 at 07:55 PM
You could serialise a Datetime either in your own file or using PlayerPrefs and then you could compare that with the current time on activation to determine how much time has elapsed since deactivating.
I don't think you can serialize a Datetime, as per https://answers.unity.com/questions/1245121/saving-systemdatetime-in-a-serialized-scriptable-o.html there must be another answer - seeing as how the TimeSpan t is always printing the correct, accelerated time.
Answer by actionjdjackson · Mar 29, 2020 at 08:25 PM
D'oh! I had another script competing for the TMP_Text component's attentions. That script did the same thing as the one in the Singleton - except it was attached to the TMP_Text and went inactive when I SetActive(true). Sorry! :)