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.
PlumberUltimateAds/Assets/TimerManager.cs

89 lines
2.3 KiB
C#

1 month ago
using System;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
public class TimerManager : MonoBehaviour
{
public TimeSpan _remainingTime;
public TimeSpan _initialTime;
1 month ago
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);
}
else
timerObj.SetActive(false);
1 month ago
}
// 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
}
}
}
}