- Home /
countdown timer starts from the begining when i reLaunch the app
hi, so i created a countdown timer script wich block the user from playing when he reachs a certain score and the user can play only when the timer reachs 00:00:00 . The problem is that the timer starts from 11:59:59 and when the user exits the app and open it again after a period, the timer starts from 11:59:59 . So, i need the timer to keep running even when the user exits the app. also i need this task to be secured as much as possible so the player can't hack it and bypass the timer. my app is connected to a server if this can help. this is my script :
private float timeRemaining = 43200;
public bool timerIsRunning = false;
public bool getTimeJustOnce = false;
public Text timerText;
private void Update()
{
int highscore = int.Parse(todayGains.text);
if(highscore == 1500)
{
startEarningButton.GetComponent<Collider2D>().enabled = false;
startEarningButton.GetComponent<Animator>().enabled = false;
if (timeRemaining > 0)
{
timeRemaining -= Time.deltaTime;
DisplayTime(timeRemaining);
PlayerPrefs.SetFloat("savedTime", timeRemaining);
}
else
{
while(timerIsRunning == true)
{
timerText.text = "";
timeRemaining = 0;
timerIsRunning = false;
startEarningButton.GetComponent<Collider2D>().enabled = true;
startEarningButton.GetComponent<Animator>().enabled = true;
PlayerPrefs.SetString("todayGains", "0");
todayGains.text = "0";
}
}
}
}
void DisplayTime(float timeToDisplay)
{
timeToDisplay -= 1;
float minutes = Mathf.FloorToInt(timeToDisplay / 60) % 60;
float seconds = Mathf.FloorToInt(timeToDisplay % 60);
float hours = Mathf.FloorToInt(timeToDisplay / 3600) % 24;
timerText.text = string.Format("ComeBack After : {0:00}:{1:00}:{2:00}", hours, minutes, seconds) ;
}
Answer by Spip5 · Aug 13, 2020 at 12:11 AM
You should watch this tutorial to save (via a file) the Time at wich the user does the trigger, and check the remaining time based on the file any time you need. That way it does not matter if the user closes the app or not. Basically it goes like this :
--> Register 2 variables on user trigger
System.DateTime userTriggerTimer = Time.Now;
System.DateTime userNextMoveTime = Time.Now.AddDays(X).AddHourse(X).AddMinutes(X).AddSeconds(X);
--> Save a file with these variables (do a System.Serialized class) (watch tutorial)
--> Load the file when you need to check (watch tutorial)
--> In a script check if the userNextMoveTime is < Time.Now (which means he is allowed to do an action)
This will 100% work if done correctly, and it is quite hard for a regular user to bypass that solution.
Also, avoid using player prefs except for settings (volume, etc..) as it's super easy to "hack". Use the tutorial i provided to save sensitive data (such as score or money)