Skip to content

Instantly share code, notes, and snippets.

@girasquid
Created July 14, 2018 17:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save girasquid/e40578f46242115385b7a6e93eecd77f to your computer and use it in GitHub Desktop.
Save girasquid/e40578f46242115385b7a6e93eecd77f to your computer and use it in GitHub Desktop.
Simple countdown timer for Unity projects that updates a Text (you supply the Text and how many seconds to start at)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[ExecuteInEditMode]
public class CountdownTimer : MonoBehaviour {
public Text timerText;
public int startingSeconds;
private float elapsedTime;
// Use this for initialization
void Start () {
elapsedTime = 0.0f;
UpdateTimerText();
}
// Update is called once per frame
void Update () {
elapsedTime += Time.deltaTime;
UpdateTimerText();
}
void UpdateTimerText() {
int timeInSeconds = (int)(elapsedTime % 60);
int minutes = 0;
int remainingSeconds = startingSeconds - timeInSeconds;
if(startingSeconds >= 60) {
minutes = (int)((startingSeconds - timeInSeconds)/60);
remainingSeconds -= (minutes * 60);
}
timerText.text = minutes.ToString() + ":" + remainingSeconds.ToString().PadLeft(2, '0');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment