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.

Revisions

  1. badscotsman created this gist Sep 22, 2022.
    35 changes: 35 additions & 0 deletions CountdownController.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    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);
    }
    }