- Home /
Prevent countdown from reloading every time a new scene is loaded
I have this countdown script which works fine, there is just the problem, that the countdown restarts every time a new scene is loaded (which it should not). Is there a way to prevent it from doing that, and just let the countdown keep going even if a new scene is loaded?
Here is my code.
static var energyObj : int = 5;
var counter : float;
function Start()
{
counter = 1800;
}
function Update () {
counter -= Time.deltaTime;
if(counter <= 0){
energyObj += 1;
counter = 1800;
Debug.Log("Energy is " + energyObj);
}
}
function OnGUI () {
var minutes = Mathf.Floor(counter / 60).ToString("00");
var seconds = (counter % 60).ToString("00");
GUI.Label(new Rect(100,40,400,40),"To Next: " + minutes + ":" + seconds);
}
You could try "Don't Destroy On Load"
http://docs.unity3d.com/Documentation/ScriptReference/Object.DontDestroyOnLoad.html
Thanks for your respond.
It sort of works, the only problem is that, it is dublicating the counter text every time the main menu loads now.
Like on the picture.
This script is attached to some gameObject. So, in this script, just check if that gameObject already exists. If it does, destroy this one. This can be done in the start method.
Answer by Fappp · Mar 24, 2014 at 08:57 PM
You could use this on end of the scene:
PlayerPrefs.SetInt("CountdownPlayerPref", countDownVariableGoesHere);
And on load of the new one use this:
countDownVariableGoesHere = PlayerPrefs.GetInt("CountdownPlayerPref");