Skip to content

Instantly share code, notes, and snippets.

@ysalihtuncel
Created July 3, 2025 12:21
Show Gist options
  • Save ysalihtuncel/2efa1fa6d143707f9f6314adb8dd6edc to your computer and use it in GitHub Desktop.
Save ysalihtuncel/2efa1fa6d143707f9f6314adb8dd6edc to your computer and use it in GitHub Desktop.
CountDownTimer
using UnityEngine;
using UnityEngine.Events;
using System.Collections;
using TMPro;
public class CountDownTimer : MonoBehaviour
{
[Header("Timer Settings")]
[SerializeField] private float startTimeInSeconds = 10f;
[SerializeField] private TMP_Text timerText;
[Header("Events")]
public UnityEvent onTimerCompleted;
private float remainingTime;
public void StartTimer(float? overrideTime = null)
{
remainingTime = overrideTime ?? startTimeInSeconds;
StartCoroutine(CountDown());
}
public void PauseTimer()
{
StopAllCoroutines();
}
public void ResumeTimer()
{
StartCoroutine(CountDown());
}
public void ResetTimer()
{
remainingTime = startTimeInSeconds;
UpdateText();
}
IEnumerator CountDown()
{
while (remainingTime > 0)
{
remainingTime--;
UpdateText();
yield return new WaitForSeconds(1f);
}
onTimerCompleted?.Invoke();
}
private void UpdateText()
{
if (timerText != null)
{
timerText.text = $"{remainingTime:F0}";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment