0
点赞
收藏
分享

微信扫一扫

Unity(二十六):定时器 - 按照指定的时间间隔来调用函数

酷子腿长一米八 2022-02-04 阅读 42

效果

脚本

using System.Collections;
using UnityEngine;
using UnityEngine.Events;

public class CubeScript : MonoBehaviour
{
    #region 运行方式一
    // private IEnumerator Start()
    // {
    //     float interval = 3f, time = 10f;
    //     yield return new SetInterval(delegate
    //     {
    //         Debug.Log($"每隔{interval}s回调一次{Time.time}");
    //     }, interval, time);
    //     Debug.Log($"{time}s时结束");
    // }
    #endregion

    #region 运行方式二

    private void Start()
    {
        StartCoroutine(IntervalFunc01());
        StartCoroutine(IntervalFunc02());
    }

    // 协同程序有暂停的时间
    private IEnumerator IntervalFunc01()
    {
        float interval = 3f, time = 10f;
        yield return new SetInterval(delegate { Debug.Log($"IntervalFunc01 ---> 每隔{interval}s回调一次{Time.time}"); }, interval, time);
        Debug.Log($"{time}s时结束");
    }

    // 协同程序持续执行
    private IEnumerator IntervalFunc02()
    {
        float interval = 3f;
        yield return new SetInterval(delegate { Debug.Log($"IntervalFunc02 ---> 每隔{interval}s回调一次{Time.time}"); }, interval);
    }

    #endregion

}

internal class SetInterval : CustomYieldInstruction
{
    // 回调函数
    private UnityAction _callback;

    // 开始时间(每次时间大于等于1s时重新赋值开始时间为当前时间,用于计算下次的时间间隔)
    private float _startTime;

    // 间隔时间    
    private float _interval;

    // 记录总时间(-1时表示无总时间)
    private float _time;

    // 0s时间(用于规定时间内停止运行函数)
    private float _zeroTime = 0f;

    public SetInterval(UnityAction callback, float interval)
    {
        // 回调函数
        _callback = callback;
        // 记录间隔调用时间
        _interval = interval;
        // 记录总时间
        _time = -1f;
    }

    public SetInterval(UnityAction callback, float interval, float time)
    {
        // 回调函数
        _callback = callback;
        // 记录间隔调用时间
        _interval = interval;
        // 记录总时间
        _time = time;
    }

    // 指示协同程序是否应保持继续执行。(要使协同程序保持暂停,则返回 /false/。要使协同程序继续执行,则返回 /true/。)
    public override bool keepWaiting
    {
        get
        {
            if (_time != -1f && Time.time - _zeroTime >= _time)
            {
                return false;
            }

            if (Time.time - _startTime >= _interval)
            {
                _startTime = Time.time;
                _callback?.Invoke();
            }
            return true;
        }
    }
}
举报

相关推荐

0 条评论