功能
倒计时结束时触发相应事件。
倒计时期间,每隔一段时间,发出事件告知外界多久后倒计时结束。
倒计时期间(未结束前),可暂停、继续、重新开始倒计时。
代码
CountDownTimer.cs
using System;
using System.Collections;
using UnityEngine;
public class CountDownTimer
{
private float _durationSeconds;
private float _intervalSeconds;
private float _remainSeconds;
private bool _isRuning;
private IEnumerator _countDownCoroutine;
// 剩余时长,总时长
public event Action<float, float> TellRemainSecondsEvent;
private Action _endAction;
public CountDownTimer(float durationSeconds, Action endAction, float intervalSeconds = 1f, bool shouldInstantlyStart = true)
{
_durationSeconds = durationSeconds;
_endAction = endAction;
_intervalSeconds = intervalSeconds;
if (shouldInstantlyStart)
{
Start();
}
}
public void MyDestroy()
{
StopCountDown();
_endAction = null;
}
public void Start()
{
StopCountDown();
ResetRemainSeonds();
Continue();
StartCountDown();
}
public void Pause()
{
_isRuning = false;
}
public void Continue()
{
_isRuning = true;
}
public void Restart()
{
if (_countDownCoroutine == null)
{
Debug.Log("倒计时已结束,无法重新开始!");
}
else
{
ResetRemainSeonds();
Continue();
}
}
public void Cancel()
{
MyDestroy();
}
private void ResetRemainSeonds()
{
_remainSeconds = _durationSeconds;
}
private void StartCountDown()
{
_countDownCoroutine = CountDownCoroutine();
MonoSys.Instance.StartCoroutine(_countDownCoroutine);
IEnumerator CountDownCoroutine()
{
var waitForSeconds = new WaitForSeconds(_intervalSeconds);
TellRemainSecondsEvent?.Invoke(_remainSeconds, _durationSeconds);
while (true)
{
yield return waitForSeconds;
if (_isRuning)
{
_remainSeconds -= _intervalSeconds;
if (_remainSeconds < 0)
{
_remainSeconds = 0;
}
TellRemainSecondsEvent?.Invoke(_remainSeconds, _durationSeconds);
if (_remainSeconds == 0)
{
_endAction?.Invoke();
break;
}
}
}
MyDestroy();
}
}
private void StopCountDown()
{
MonoSys.Instance.DestroyCoroutine(ref _countDownCoroutine);
}
}
网友评论