- Home /
Keeping track of time after calling Application.LoadLevel
Hello, I'd like some advice and a general direction for how to implement a certain game mechanic. I'm not sure if my current methods are viable or not.
I have a scene with a GameObject myGameObject
which uses DateTime
s and TimeSpan
for a timer to execute a method once the TimeSpan
reaches zero.
I would like the player to be able to move to a different scene where myGameObject
isn't present on the screen, however still have the timer count down and the method executed as time passes.
Using Application.LoadLevel
to move the player to a new level/scene destroys all current GameObjects and my countdown method is interrupted.
DontDestroyOnLoad()
doesn't seem helpful as the new scene should not have myGameObject
present.
Will I have to redesign my game to not require LoadLevel to load new levels, and instead create my own level loading script that operates in a single scene?
Is there a way to continuously keep track of time and execute the method even after Application.LoadLevel has been called?
Answer by mindlube · Jul 21, 2012 at 03:32 AM
DontDestroyOnLoad : "Makes the object target not be destroyed automatically when loading a new scene. " That's what you want right? If that doesn't work for you, or it's too complicated. (it does add complexity to your scenes) Then sounds like a good use case for PlayerPrefs! Just drop this component into some gameobject in every scene you want to try the time in. Hope this helps
using UnityEngine;
using System;
public class TimeTracker : MonoBehaviour
{
public DateTime LastTime { get; set; }
public static string PrefsKey = "last time";
public void Awake()
{
if(PlayerPrefs.HasKey(PrefsKey))
{
var ticks = long.Parse( PlayerPrefs.GetString( PrefsKey ) );
LastTime = new DateTime( ticks );
}
else
{
LastTime = DateTime.Now;
}
}
public void OnDestroy()
{
PlayerPrefs.SetString( PrefsKey, LastTime.Ticks.ToString() );
PlayerPrefs.Save();
}
}
Your answer
Follow this Question
Related Questions
time between scenes (loading time) 0 Answers
I need help for delete old highscore 0 Answers
Quit application before relaunching to specific scene 1 Answer
Problems editing a level from script 1 Answer
Loading A Level After 40 Seconds 2 Answers