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

113 lines
2.5 KiB
C#
Raw Normal View History

2025-03-03 13:01:04 +08:00
using Cysharp.Threading.Tasks;
using Gameplay;
using System;
using System.Text;
2025-04-28 13:03:28 +08:00
public class TimerText
2025-03-03 13:01:04 +08:00
{
2025-04-28 10:00:55 +08:00
private TimerTextTimer _timerTextTimer;
2025-03-03 13:01:04 +08:00
private TMPro.TextMeshProUGUI text;
2025-04-28 13:03:28 +08:00
public void Init(TMPro.TextMeshProUGUI text)
2025-03-03 13:01:04 +08:00
{
2025-04-28 10:00:55 +08:00
if (_timerTextTimer == null)
2025-03-03 13:01:04 +08:00
{
2025-04-28 13:03:28 +08:00
_timerTextTimer = new TimerTextTimer();
}
this.text = text;
}
public void SetTimer(float time)
{
if (_timerTextTimer == null || text == null)
{
DebugUtil.LogError("<22><>δ<EFBFBD><CEB4>ʼ<EFBFBD><CABC>TimerText, <20><><EFBFBD>ȵ<EFBFBD><C8B5><EFBFBD>Init<69><74><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>г<EFBFBD>ʼ<EFBFBD><CABC><EFBFBD><EFBFBD>");
return;
2025-03-03 13:01:04 +08:00
}
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();
}
}
}
}