NLDClient-yudde/ProjectNLD/Assets/Code/Scripts/Gameplay/Utils/TimerText.cs

106 lines
2.3 KiB
C#
Raw Normal View History

2025-03-03 13:01:04 +08:00
using Cysharp.Threading.Tasks;
using Gameplay;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
public class TimerText : MonoBehaviour
{
2025-04-28 10:00:55 +08:00
private TimerTextTimer _timerTextTimer;
2025-03-03 13:01:04 +08:00
private TMPro.TextMeshProUGUI text;
public void SetTimer(float time)
{
2025-04-28 10:00:55 +08:00
if (_timerTextTimer == null)
2025-03-03 13:01:04 +08:00
{
2025-04-28 10:00:55 +08:00
_timerTextTimer = new TimerTextTimer();
2025-03-03 13:01:04 +08:00
text = GetComponent<TMPro.TextMeshProUGUI>();
}
2025-04-28 10:00:55 +08:00
_timerTextTimer.SetTimer(time);
2025-03-03 13:01:04 +08:00
}
public void StartTimer()
{
2025-04-28 10:00:55 +08:00
_timerTextTimer.StartTimer();
_timerTextTimer.OnValueChanged += OnValueChange;
2025-03-03 13:01:04 +08:00
}
public void StopTimer()
{
2025-04-28 10:00:55 +08:00
_timerTextTimer.StopTimer();
_timerTextTimer.OnValueChanged -= OnValueChange;
2025-03-03 13:01:04 +08:00
}
void OnValueChange(float time)
{
TimeSpan remains = TimeSpan.FromSeconds(time);
var day = remains.Days;
var hour = remains.Hours;
var minute = remains.Minutes;
var second = remains.Seconds;
StringBuilder sb = new StringBuilder();
sb.Append(CommonUtils.GetLocalizeText("ʣ<><CAA3>"));
if (day > 0)
sb.Append($"{day}d {hour:D2}h");
else if (hour > 0)
sb.Append($"{hour:D2}h {minute:D2}m {second:D2}s");
else if (minute > 0)
sb.Append($"{minute:D2}m {second:D2}s");
else
sb.Append($"{second:D2}s");
text.text = sb.ToString();
}
}
2025-04-28 10:00:55 +08:00
public class TimerTextTimer
2025-03-03 13:01:04 +08:00
{
private float RemainingTime;
private bool IsRunning;
public delegate void OnValueChange(float time);
public event OnValueChange OnValueChanged;
public delegate void OnTimerEnd();
public event OnTimerEnd OnTimerEndEvent;
public void SetTimer(float time)
{
RemainingTime = time;
}
public void StartTimer()
{
if (IsRunning)
return;
IsRunning = true;
CoreTimer();
}
public void StopTimer()
{
IsRunning = false;
}
async void CoreTimer()
{
while (IsRunning)
{
await UniTask.Delay(1000);
RemainingTime--;
OnValueChanged?.Invoke(RemainingTime);
if (RemainingTime <= 0)
{
StopTimer();
OnTimerEndEvent?.Invoke();
}
}
}
}