Skip to content

Instantly share code, notes, and snippets.

@badscotsman
Created September 22, 2022 08:28
Show Gist options
  • Save badscotsman/4a3c24c2ab4faa985dea44a7dd6b8faa to your computer and use it in GitHub Desktop.
Save badscotsman/4a3c24c2ab4faa985dea44a7dd6b8faa to your computer and use it in GitHub Desktop.
A reusable countdown controller component for Unity.
using UnityEngine;
using UnityEngine.Events;
using TMPro;
public class CountdownController : MonoBehaviour
{
[SerializeField] private int _count = 3;
[SerializeField] private TMP_Text _countdownLabel;
[SerializeField] private string _countdownFinishText = "Go!";
public UnityEvent OnCountdownFinish;
void Start()
{
_countdownLabel.SetText(_count.ToString());
InvokeRepeating(nameof(Countdown), 1f, 1f);
}
private void Countdown()
{
_countdownLabel.SetText((--_count == 0) ? _countdownFinishText : _count.ToString());
if (_count == 0)
{
CancelInvoke();
Invoke(nameof(DisableCountdown), 1f);
}
}
private void DisableCountdown()
{
_countdownLabel.gameObject.SetActive(false);
OnCountdownFinish?.Invoke();
Destroy(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment