效果

脚本
using System.Collections;
using UnityEngine;
using UnityEngine.Events;
public class CubeScript : MonoBehaviour
{
#region 运行方式一
#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;
private float _startTime;
private float _interval;
private float _time;
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;
}
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;
}
}
}