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扫码关注 ->当前文章末尾 获取

欢迎关注


在这里插入图片描述

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值