Created
July 3, 2025 12:21
-
-
Save ysalihtuncel/2efa1fa6d143707f9f6314adb8dd6edc to your computer and use it in GitHub Desktop.
CountDownTimer
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 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