58 lines
1.3 KiB
C#
58 lines
1.3 KiB
C#
using UnityEngine;
|
|
using TMPro;
|
|
using System.Collections;
|
|
|
|
public class CrateEscapeTimer : MonoBehaviour
|
|
{
|
|
[Header("UI")]
|
|
public TMP_Text timerText; // Assign a TextMeshProUGUI on your world canvas
|
|
|
|
[Header("Timer")]
|
|
public int startSeconds = 120; // 2 minutes
|
|
public bool autoStart = true;
|
|
|
|
private int _remaining;
|
|
private Coroutine _routine;
|
|
|
|
void Awake()
|
|
{
|
|
if (!timerText)
|
|
timerText = GetComponent<TMP_Text>();
|
|
}
|
|
|
|
void OnEnable()
|
|
{
|
|
if (autoStart) StartTimer();
|
|
}
|
|
|
|
public void StartTimer(int? overrideSeconds = null)
|
|
{
|
|
if (_routine != null) StopCoroutine(_routine);
|
|
_remaining = overrideSeconds ?? startSeconds;
|
|
UpdateLabel(_remaining);
|
|
_routine = StartCoroutine(Tick());
|
|
}
|
|
|
|
IEnumerator Tick()
|
|
{
|
|
while (_remaining > 0)
|
|
{
|
|
yield return new WaitForSeconds(1f);
|
|
_remaining--;
|
|
UpdateLabel(_remaining);
|
|
}
|
|
|
|
// Time's up!
|
|
UpdateLabel(0);
|
|
if (CrateEscapeGameManager.Instance != null)
|
|
CrateEscapeGameManager.Instance.GameOver();
|
|
}
|
|
|
|
private void UpdateLabel(int seconds)
|
|
{
|
|
int m = seconds / 60;
|
|
int s = seconds % 60;
|
|
if (timerText) timerText.text = $"{m:00}:{s:00}";
|
|
}
|
|
}
|