hi!
I have a problem with the time that manages energy: once I lose an energy, a countdown starts at the end of which I get an energy. However, if I close the game when the countdown is set a few seconds after the energy is restored and I return to the game, I rightly receive an energy but shortly afterwards it gives me another extra. It seems that the contdown since the return of the game has restarted since I closed the game. How can I do?
thanks!
public string saveLocation;
private const float establishedTime = 120f;//1800f
public float timer;
private float timePassed;
private GameData gameData;
private bool timerEnd = false;
private bool openGame = true;
public float Timer
{
get
{
return timer;
}
set
{
timer = Mathf.Clamp(value, 0,value);
}
}
private void Awake()
{
me = this;
gameData = FindObjectOfType<GameData>();
timerEnd = false;
saveLocation = "lastDate";
}
void Start () {
if (gameData.return && gameDatai.lost && gameData howEnergy == gameData.maxEnergy - 1)
{
SaveData();
}
if( gameData.howEnergy < gameData.maxEnergy)//
{
nEnergiesEarned = (int)(timePassed / establishedTime);
Add(nEnergiesEarned);
if (howEnergy < gameData.maxEnergy )
{
if (timePassed > establishedTime)
Timer = timePassed % establishedTime;
else Timer = ttimePassed - establishedTime;
}
openGame = true;
}
public float CheckDate()
{
currentDate = System.DateTime.Now;
string tempSting = PlayerPrefs.GetString(saveLocation, "1");
long tempLong = Convert.ToInt64(tempSting);
DateTime oldDate = DateTime.FromBinary(tempLong);
TimeSpan diff = dataCorrente.Subtract(oldDate);
return (float)diff.TotalSeconds;
}
public void SaveData()
{
PlayerPrefs.SetString(saveLocation, System.DateTime.Now.ToBinary().ToString());
PlayerPrefs.Save();
``}
public void Add(int energy)
{
gameData.howEnergy += energy;
PlayerPrefs.SetInt("enBase", gameData.howEnergy);
PlayerPrefs.Save();
}
public void Restart()
{
if (openGame)
{
StartCoroutine(Test());
return;
}
if ( Timer == 0)
{
timeEnd = true;
}
if (tempoEnd && !openGame){
Timer = establishedTime;//1800f
SaveData();
Add(1);
timeEnd = false;
}
}
IEnumerator Test()
{
yield return new WaitForSeconds(1f);
openGame = false;
}
// Update is called once per frame
void Update () {
if (gameData.extraEnergy == 0)
{
if ( gameData.howEnergy < gameData.maxEnergy)
Timer -= Time.deltaTime;
}
Reset();
}