I have this code, which has an integer of 5 and then a countdown which counts down from 30 minutes. If you loose a level, it subtracts one from the integer and then every 30 minute, it adds one to the integer. Now the problem is, that when i close the game(it’s for iOS) and i open it again 10 seconds later, the integer has been set back to 5 and the timer is set back to 30 and isn’t running.
I have tried making a bit of the code when closing the game and loading it, but i can’t seem to figure out how to subtract the time on quit with the time on load and then find the difference and subtract that with what the “counter” was on quit.
Here is my script.
static var energyObj : int = 5;
static var showC : boolean = true;
private static var created = false;
var counter : float;
var quitGame : boolean = false;
function Start()
{
counter = 1800;
}
function Update () {
if (energyObj < 5) {
counter -= Time.deltaTime;
if(counter <= 0){
energyObj += 1;
counter = 1800;
Debug.Log("Energy is " + energyObj);
}
}
energyObj = Mathf.Clamp(energyObj, 0, 5);
if (energyObj > 5) {
energyObj = 5;
}
if (energyObj < 0) {
energyObj = 0;
}
}
function OnGUI () {
if (energyObj < 5) {
var minutes = Mathf.Floor(counter / 60).ToString("00");
var seconds = (counter % 60).ToString("00");
if (showC == true){
GUI.Label(new Rect(100,40,400,40),"To Next: " + minutes + ":" + seconds);
}
}
}
Here is the code for closing and loading the game.
function OnApplicationQuit() {
quitGame = true;
if (quitGame == true) {
PlayerPrefs.SetFloat("lastCounter",counter);
PlayerPrefs.SetInt("lastEnergyObj",energyObj);
PlayerPrefs.SetString("lastTimeSaved",System.DateTime.Now.ToBinary().ToString());
Debug.Log("time now is : " + System.DateTime.Now);
Debug.Log("energy is : " + energyObj);
Debug.Log("last counter is: " + counter);
} else if (quitGame == false) {
PlayerPrefs.GetInt("lastEnergyObj");
PlayerPrefs.GetString("lastTimeSaved");
PlayerPrefs.GetFloat("lastCounter");
var timeDifference : float = System.DateTime.Now - lastTimeSaved;
counter = timeDifference - counter;
ernergyObj = lastEnergyObj;
}
}