Unity中实现倒计时

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

在这里插入图片描述

核心代码:

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; }
}

部分实现代码:

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

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

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

使用方式:

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

欢迎关注


在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/JianZuoGuang/article/details/90045205