using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 提供了协程实现的倒计时封装
/// </summary>
public class XCTime : MonoBehaviour
{
/// <summary>
/// 回调函数
/// </summary>
private Action<int, int> callback;
/// <summary>
/// 总的CD
/// </summary>
private int totalSeconds;
/// <summary>
/// 剩余的CD
/// </summary>
private int surplusSeconds;
/// <summary>
/// 是否需要初始化
/// </summary>
private Boolean isNeedInited;
/// <summary>
/// 开始倒计时
/// </summary>
/// <param name="callback">回调函数 剩余秒数,总秒数</param>
/// <param name="totalSeconds">总的秒数</param>
/// <param name="isNeedInited">是否需要初始化(直接调用一次回调)</param>
public void StartCD( Action<int,int> callback , int totalSeconds , Boolean isNeedInited = true )
{
this.StopCD();
this.callback = callback;
this.totalSeconds = totalSeconds;
this.surplusSeconds = totalSeconds;
this.isNeedInited = isNeedInited;
if (this.totalSeconds <= 0)
{
if (this.isNeedInited) {
this.callback(0, 0);
}
this.Clear(false);
}
else
{
if (this.isNeedInited)
{
this.callback(this.surplusSeconds, this.totalSeconds);
}
this.StartCoroutine(this.CountDown());//开启倒计时
}
}
/// <summary>
/// 停止倒计时
/// </summary>
public void StopCD()
{
this.StopCoroutine(this.CountDown());
}
/// <summary>
/// 申明倒计时协程函数
/// </summary>
/// <returns></returns>
private IEnumerator CountDown()
{
while (true)
{
yield return new WaitForSeconds(1);//每一秒执行1次
this.surplusSeconds--;
this.callback(this.surplusSeconds, this.totalSeconds);
if (this.surplusSeconds <= 0)
{
this.Clear(true);
break;
}
}
}
private void Clear( Boolean isNeedStop )
{
if (isNeedStop)
{
this.StopCD();
}
if (this.callback != null)
{
this.callback = null;
}
}
public void OnDestroy()
{
this.Clear(true);
}
}