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

113 lines
2.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using Cysharp.Threading.Tasks;
using Gameplay;
using System;
using System.Text;
public class TimerText
{
private TimerTextTimer _timerTextTimer;
private TMPro.TextMeshProUGUI text;
public void Init(TMPro.TextMeshProUGUI text)
{
if (_timerTextTimer == null)
{
_timerTextTimer = new TimerTextTimer();
}
this.text = text;
}
public void SetTimer(float time)
{
if (_timerTextTimer == null || text == null)
{
DebugUtil.LogError("暂未初始化TimerText, 请先调用Init方法进行初始化");
return;
}
_timerTextTimer.SetTimer(time);
}
public void StartTimer()
{
_timerTextTimer.StartTimer();
_timerTextTimer.OnValueChanged += OnValueChange;
}
public void StopTimer()
{
_timerTextTimer.StopTimer();
_timerTextTimer.OnValueChanged -= OnValueChange;
}
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("剩余"));
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();
}
}
public class TimerTextTimer
{
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();
}
}
}
}