Created
September 22, 2022 08:28
-
-
Save badscotsman/4a3c24c2ab4faa985dea44a7dd6b8faa to your computer and use it in GitHub Desktop.
A reusable countdown controller component for Unity.
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 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