20 minute countdown timer
Hey guys, I have a countdown timer but am unsure of how to make it twenty minutes? I would appreciate any help. Thanks :)
public Text timerText;
private float time = 1200;
void Update() {
time += Time.deltaTime;
var minutes = time / 60;
var seconds = time - 60;
var fraction = (time * 100) % 100;
//update the label value
timerText.text = string.Format ("{0:00} : {1:00} : {2:000}", minutes, seconds, fraction);
}
}
Comment
Best Answer
Answer by TBruce · Apr 21, 2016 at 04:28 PM
Try the following. It uses less CPU cycles as well.
public Text timerText;
private float time = 1200;
void Start ()
{
StartCoundownTimer();
}
void StartCoundownTimer()
{
if (timerText != null)
{
time = 1200;
timerText.text = "Time Left: 20:00:000";
InvokeRepeating("UpdateTimer", 0.0f, 0.01667f);
}
}
void UpdateTimer()
{
if (timerText != null)
{
time -= Time.deltaTime;
string minutes = Mathf.Floor(time / 60).ToString("00");
string seconds = (time % 60).ToString("00");
string fraction = ((time * 100) % 100).ToString("000");
timerText.text = "Time Left: " + minutes + ":" + seconds + ":" + fraction;
}
}
void Update(){ time -= Time.deltaTime; if(time < 0) { //Do Something }
Answer by MyrDovg · Oct 30, 2017 at 11:32 AM
float totalTime = 120f; //2 minutes
private void Update()
{
totalTime -= Time.deltaTime;
UpdateLevelTimer(totalTime );
}
public void UpdateLevelTimer(float totalSeconds)
{
int minutes = Mathf.FloorToInt(totalSeconds / 60f);
int seconds = Mathf.RoundToInt(totalSeconds % 60f);
string formatedSeconds = seconds.ToString();
if (seconds == 60)
{
seconds = 0;
minutes += 1;
}
timer.text = minutes.ToString("00") + ":" + seconds.ToString("00");
}