Unity3D之使用协程实现倒计时
  RlWeLU85QNwT 2023年11月02日 56 0

一, 场景设置

Unity3D之使用协程实现倒计时_倒计时


二, 脚本

Ⅰ, 封装协程倒计时类(相当于工具) XCTime.as

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

Ⅱ, 使用工具的脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// 此脚本用于测试倒计时
/// </summary>
[RequireComponent(typeof(XCTime))]
public class CountDownDemo : MonoBehaviour
{
private XCTime cdHelper;
private Text txtCD;
// Start is called before the first frame update
void Start()
{
this.cdHelper = this.gameObject.GetComponent<XCTime>();
this.txtCD = this.gameObject.transform.Find("TxtCD").GetComponent<Text>();

this.cdHelper.StartCD(this.ResetCD, 100, true);//开始倒计时
}

private void ResetCD(int surplus, int total)
{
this.txtCD.text = surplus.ToString();//更新数据
}
}

三, 挂载脚本

Unity3D之使用协程实现倒计时_协程_02

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

RlWeLU85QNwT