Skip to content

Instantly share code, notes, and snippets.

@Dssdiego
Last active March 2, 2020 19:55
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 Dssdiego/f57fd0e8ef92c2034257bf9ee7c576b5 to your computer and use it in GitHub Desktop.
Save Dssdiego/f57fd0e8ef92c2034257bf9ee7c576b5 to your computer and use it in GitHub Desktop.
Unity Countdown Timer (MM:SS)
using System;
using System.Collections;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
[RequireComponent(typeof(TextMeshProUGUI))]
public class Timer : MonoBehaviour
{
private TextMeshProUGUI textUI;
private float currentTime;
private bool isRunning = true;
[Header("Events")]
public UnityEvent timerEnded;
[Header("Control")]
[SerializeField] private string time;
void Start()
{
textUI = GetComponent<TextMeshProUGUI>();
StartCoroutine(nameof(CountDown));
}
IEnumerator CountDown() {
ConvertStringToTime();
while (isRunning) {
if (currentTime > 0.5f) {
currentTime -= 1;
textUI.SetText(ConvertToTime(currentTime));
}
else {
isRunning = false;
timerEnded.Invoke();
}
yield return new WaitForSeconds(1);
}
}
private String ConvertToTime(float seconds) {
return TimeSpan.FromSeconds(seconds).ToString(@"mm\:ss");
}
private void ConvertStringToTime()
{
string[] s = time.Split(':');
float minutes = float.Parse(s[0]);
float seconds = float.Parse(s[1]);
currentTime = minutes * 60 + seconds;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment