Last active
March 2, 2020 19:55
-
-
Save Dssdiego/f57fd0e8ef92c2034257bf9ee7c576b5 to your computer and use it in GitHub Desktop.
Unity Countdown Timer (MM:SS)
This file contains hidden or 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; | |
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