I tried to refill player lives over countdown time, but the problem is when lives are full, when scene is reload, lives are decreasing one by one.
How to fix this ?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class LivesCounterRefill : MonoBehaviour
{
[SerializeField] private Text livesCount;
[SerializeField] private Text Timer;
[SerializeField] private int MaxLivesCount;
private int totalHCount;
private DateTime nextHCountTime;
private DateTime lastAddedTime;
public int restoreduration = 10;
private bool restoring = false;
void Start()
{
Load();
StartCoroutine(RestoreRoutine());
}
void Update()
{
UpdateTimer();
UpdateHCount();
}
IEnumerator RestoreRoutine()
{
restoring = true;
while (totalHCount < MaxLivesCount)
{
DateTime currentTime = DateTime.Now;
DateTime Counter = nextHCountTime;
bool isAdding = false;
while (currentTime > Counter)
{
if (totalHCount < MaxLivesCount)
{
isAdding = true;
totalHCount++;
DateTime timeToAdd = lastAddedTime > Counter ? lastAddedTime : Counter;
Counter = AddDuration(timeToAdd, restoreduration);
}
else
break;
}
if (isAdding)
{
lastAddedTime = DateTime.Now;
nextHCountTime = Counter;
}
UpdateTimer();
UpdateHCount();
save();
yield return null;
}
restoring = false;
}
void UpdateTimer()
{
if (totalHCount >= MaxLivesCount)
{
Timer.text = "Full";
return;
}
TimeSpan tan = nextHCountTime - DateTime.Now;
string value = String.Format("{0:D2}:{1:D2}", tan.Minutes, tan.Seconds);
Timer.text = value;
}
private void UpdateHCount()
{
livesCount.text = totalHCount.ToString();
}
private DateTime AddDuration(DateTime time, int duration)
{
return time.AddMinutes(duration);
}
void Load()
{
nextHCountTime = StringToDate(PlayerPrefs.GetString("nextHCountTime"));
lastAddedTime = StringToDate(PlayerPrefs.GetString("lastAddedTime"));
totalHCount = PlayerPrefs.GetInt("PLC1");//value from lives counter
}
void save()
{
PlayerPrefs.SetString("nextHCountTime", nextHCountTime.ToString());
PlayerPrefs.SetString("lastAddedTime", lastAddedTime.ToString());
PlayerPrefs.SetInt("PLC2", totalHCount);//out put value
}
DateTime StringToDate(string date)
{
if (String.IsNullOrEmpty(date))
return DateTime.Now;
return DateTime.Parse(date);
}
}