You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
87 lines
2.2 KiB
C#
87 lines
2.2 KiB
C#
1 month ago
|
using System;
|
||
|
using TMPro;
|
||
|
using UnityEngine;
|
||
|
using UnityEngine.Events;
|
||
|
using UnityEngine.UI;
|
||
|
|
||
|
public class TimerManager : MonoBehaviour
|
||
|
{
|
||
|
private TimeSpan _remainingTime;
|
||
|
private TimeSpan _initialTime;
|
||
|
private bool _isTimerRunning;
|
||
|
|
||
|
// Event triggered when the timer starts
|
||
|
public event Action TimerStarted;
|
||
|
|
||
|
// Event triggered when the timer ends
|
||
|
//public event Action TimerEnded;
|
||
|
public UnityEvent TimerEnded = new UnityEvent();
|
||
|
public TextMeshProUGUI timer;
|
||
|
public GameObject timerObj;
|
||
|
public GameObject gameoverPanelObj;
|
||
|
|
||
|
//public Textmeshprougui timertext;
|
||
|
private void Start()
|
||
|
{
|
||
|
if (GamePlayManager.isTimerLevel)
|
||
|
{
|
||
|
timerObj.SetActive(true);
|
||
|
InitializeTimer(0, 2, 0);
|
||
|
}
|
||
|
|
||
|
}
|
||
|
// Initialize the timer with hours, minutes, and seconds
|
||
|
public void InitializeTimer(int hours, int minutes, int seconds)
|
||
|
{
|
||
|
_initialTime = new TimeSpan(hours, minutes, seconds);
|
||
|
_remainingTime = _initialTime;
|
||
|
StartTimer();
|
||
|
}
|
||
|
|
||
|
// Start the timer
|
||
|
public void StartTimer()
|
||
|
{
|
||
|
if (_remainingTime.TotalSeconds > 0 && !_isTimerRunning)
|
||
|
{
|
||
|
_isTimerRunning = true;
|
||
|
TimerStarted?.Invoke(); // Trigger the TimerStarted event
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// Stop the timer
|
||
|
public void StopTimer()
|
||
|
{
|
||
|
_isTimerRunning = false;
|
||
|
}
|
||
|
|
||
|
// Reset the timer to its initial value
|
||
|
public void ResetTimer()
|
||
|
{
|
||
|
StopTimer();
|
||
|
_remainingTime = _initialTime;
|
||
|
}
|
||
|
|
||
|
// Get the remaining time
|
||
|
public TimeSpan GetRemainingTime()
|
||
|
{
|
||
|
return _remainingTime;
|
||
|
}
|
||
|
|
||
|
// Update is called once per frame
|
||
|
void Update()
|
||
|
{
|
||
|
if (_isTimerRunning)
|
||
|
{
|
||
|
// Subtract deltaTime from the remaining time
|
||
|
_remainingTime = _remainingTime.Subtract(TimeSpan.FromSeconds(Time.deltaTime));
|
||
|
timer.text = _remainingTime.ToString("m\\:ss");
|
||
|
// If the timer has reached 0 or less, stop it
|
||
|
if (_remainingTime.TotalSeconds <= 0)
|
||
|
{
|
||
|
_remainingTime = TimeSpan.Zero;
|
||
|
_isTimerRunning = false;
|
||
|
TimerEnded?.Invoke(); // Trigger the TimerEnded event
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|