valentincognito
9/15/2017 - 5:15 AM

Countdown

Simple countdown implementation

using UnityEngine;
using UnityEngine.UI;

public class Countdown : MonoBehaviour {

    public Text placeholder;
    public float numberOfSeconds;
    public bool showMinutes;
    public bool isStarted;

    public float timeLeft;
    private float minutes;
    private float seconds;

    private void Start()
    {
        ResetCountdown();
    }

    private void Update()
    {
        if (isStarted) StartCountdown();
    }

    public void StartCountdown()
    {
        timeLeft -= Time.deltaTime;

        if (timeLeft <= 0) return;

        if (!showMinutes)
        {
            placeholder.text = timeLeft.ToString("N0").PadLeft(2, '0');
        }
        else
        {
            minutes = Mathf.Floor(timeLeft / 60);
            seconds = timeLeft % 60;
            placeholder.text = minutes.ToString("N0").PadLeft(2, '0') + ":" + seconds.ToString("N0").PadLeft(2, '0');
        }
    }

    public void ResetCountdown()
    {
        timeLeft = numberOfSeconds;
        placeholder.text = timeLeft.ToString("N0").PadLeft(2, '0');
    }
}