Created
July 14, 2018 17:49
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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