Unity中实现倒计时

Unity中使用Coroutine(协程)实现倒计时功能

Unity中实现倒计时_第1张图片

核心代码:

do {
        currentMinute = minute;
            do {
                while (pause) {
                    yield return null;
                }
                second--;
                if (OnCountDowning != null) {
                    OnCountDowning (minute, second);
                }
                yield return new WaitForSeconds (1);
            } while (second > 0);
            second = 60;
            minute--;
        } while (minute >= 0);

定义接口定义闹钟的基础功能:

public interface ICountDown {
    void StartCountDown ();
    void StopCountDown ();
    Action OnCountDownStart { get; set; }
    Action OnCountDownEnd { get; set; }
    Action OnCountDownPause { get; set; }
    Action<int, int> OnCountDowning { get; set; }
    bool Pause { get; set; }
}

部分实现代码:

    /// 
    /// 开始计时回调
    /// 
    /// 
    public Action OnCountDownStart { get; set; }
    /// 
    /// 计时结束回调
    /// 
    /// 
    public Action OnCountDownEnd { get; set; }
    /// 
    /// 计时暂停回调
    /// 
    /// 
    public Action OnCountDownPause { get; set; }
    /// 
    /// 计时过程回调
    /// 
    /// int分别代表分钟数和秒钟数
    public Action<int, int> OnCountDowning { get; set; }

    [SerializeField][Header ("分钟")]
    private int minutes = 0;
    [SerializeField][Header ("秒钟")]
    private int seconds = 0;

    [SerializeField]
    private bool pause = false;
    /// 
    /// 暂停当前倒计时
    /// 
    public bool Pause {
        get { return pause; }
        set {
            pause = value;
            if (OnCountDownEnd != null) {
                OnCountDownEnd ();
                Debug.Log ("时间暂停");
            }
        }
    }
    /// 
    /// 当前秒钟数
    /// 
    /// 
    public int currentSecond { get; private set; }
    /// 
    /// 当前分钟数
    /// 
    /// 
    public int currentMinute { get; private set; } //代表当前分钟数

使用方式:

话不多说,Demo中都有,Demo扫码关注 ->当前文章末尾 获取

欢迎关注


Unity中实现倒计时_第2张图片

你可能感兴趣的:(Unity3D)