Files
Crash-Course/Assets/Scripts/Game/GameTimer.cs

61 lines
1.4 KiB
C#
Raw Normal View History

2025-03-25 11:34:24 -04:00
using TMPro;
2025-04-16 19:57:54 -04:00
using UnityEngine; using Game; using Music; using Player;
2025-03-20 14:45:29 -04:00
using UnityEngine.UI;
2025-04-16 19:57:54 -04:00
namespace Game
{
2025-03-20 14:45:29 -04:00
public class GameTimer : MonoBehaviour
{
public float startTime = 180f;
private float timeRemaining;
private bool timerRunning = false;
public Text timerText;
2025-03-25 11:34:24 -04:00
[SerializeField] private TextMeshProUGUI timer;
2025-03-20 14:45:29 -04:00
private void Start()
{
timeRemaining = startTime;
2025-03-25 22:21:21 -04:00
timer.text = "3:00.00";
2025-03-20 14:45:29 -04:00
UpdateTimerDisplay();
}
private void Update() // Updates the timer to show the time remaining
2025-03-20 14:45:29 -04:00
{
if (timerRunning)
{
timeRemaining -= Time.deltaTime;
if (timeRemaining <= 0)
{
timeRemaining = 0;
timerRunning = false;
OnTimerEnd();
}
UpdateTimerDisplay();
}
}
public void StartTimer() // Starts the timer
2025-03-20 14:45:29 -04:00
{
if (!timerRunning)
{
timeRemaining = startTime;
timerRunning = true;
}
}
private void UpdateTimerDisplay() // Formats and sets the time remaining
2025-03-20 14:45:29 -04:00
{
int minutes = Mathf.FloorToInt(timeRemaining / 60);
int seconds = Mathf.FloorToInt(timeRemaining % 60);
2025-03-25 22:21:21 -04:00
timer.text = string.Format("{0}:{1:D2}", minutes, seconds);
2025-03-20 14:45:29 -04:00
}
private void OnTimerEnd() // Ends the game when the time runs out
2025-03-20 14:45:29 -04:00
{
GameManager.Instance.GameOver();
}
}
2025-04-16 19:57:54 -04:00
}