Reward Timer in Unity
- santosh nalla
- Jul 31, 2020
- 2 min read
Before reading this blog, i strongly recommend you to read my previous blog on Daily Reward Bonus.
Here in this blog lets talk on how to achieve reward timer in unity. If you have played mobile games, you could have seen a timer running on the screen and once it runs out, you can claim your reward. This is reward timer. It runs not only when you open your application but also when you close it.
To run a regular timer, which ONLY runs when you open your application is pretty easy right? But the tricky part is how do you run a countdown/timer and let it continue every time you close and open your application.
As i explained in my previous blog, this can be achieved by combination of SystemDate library and PlayerPrefs.
Here is a very simple logic to achieve this:
The very first time you open your application, add counter time you want(lets suppose 24 hours) to current time and store it in playerpref variable(LETS SAY COUNTER) as string. This is constant and you wont be changing this.
So every other time you open the application, you subtract current time with COUNTER you have saved previously. So this creates a counter for you.
Code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
public class RewardTimer : MonoBehaviour
{
[SerializeField] GameObject _timeText;
[SerializeField] Button _specialCarButton;
[SerializeField] int _counterHours;
DateTime _added;
void Start()
{
if (PlayerPrefs.GetInt("FirstTimerSet", 0) == 0)
{
_added = System.DateTime.Now.AddHours(_counterHours);
PlayerPrefs.SetInt("FirstTimerSet", 1);
PlayerPrefs.SetString("TimeCounter", _added.ToString());
}
else
{
PlayerPrefs.GetString("TimeCounter");
_added = System.DateTime.Parse(PlayerPrefs.GetString("TimeCounter"));
}
}
// Update is called once per frame
void Update()
{
if (!(_added.Subtract(System.DateTime.Now).Seconds < 0))
{
if (_timeText.GetComponent<TextMeshProUGUI>().enabled)
_timeText.GetComponent<TextMeshProUGUI>().text = "UNLOCK TIME: " + _added.Subtract(System.DateTime.Now).Hours.ToString("00") + ":" + _added.Subtract(System.DateTime.Now).Minutes.ToString("00") + ":" + _added.Subtract(System.DateTime.Now).Seconds.ToString("00");
_specialCarButton.interactable = false;
}
else
{
_timeText.GetComponent<TextMeshProUGUI>().text = "CLAIM NOW";
_specialCarButton.interactable = true;
}
}
}
_counterHours is how many hours timer you wanna create.
_timeText is text field where timer is displayed
_specialCarButton is button which gets activated once the timer runs out!!
Final Result:
Happy coding, Thank you.
Comments