InvokeRepeating
在 Unity 中按照指定的时间间隔重复调用某个方法。
InvokeRepeating(string methodName, float time, float repeatRate)
methodName:要重复调用的方法的名称(字符串形式)。
time:首次调用该方法之前的延迟时间(以秒为单位)。
repeatRate:每次调用之间的时间间隔(以秒为单位)。
我总是混淆第二个参数的概念,还是记录一下吧。
System.Threading.Timer
Timer 通常用于在指定的时间间隔后执行任务或周期性地执行任务。它可以帮助实现定时操作,确保任务按照预定的时间计划进行。
Timer timer = new Timer(TimerCallback, stateObject, dueTime, period);
TimerCallback 是回调函数,即到达指定时间时要执行的方法。
stateObject 是一个用户自定义的对象,可以传递给回调函数用于传递数据。
dueTime 是首次执行回调函数之前的延迟时间(以毫秒为单位)。如果设置为 0,则立即执行。
period 是回调函数执行的时间间隔(以毫秒为单位)。如果设置为 Timeout.Infinite,则只执行一次。
在unity中使用示例:
using System;
using System.Threading;
public class PrintEveryTenSeconds : MonoBehaviour
{
private Timer timer;
void Start()
{
timer = new Timer(TimerCallback, null, 0, 10000);
}
private void TimerCallback(object state)
{
Debug.Log("每隔 10 秒打印");
}
void OnDestroy()
{
timer.Dispose();
}
}
踩坑:TimerCallback方法里开启unity的协程,不会执行协程的代码
System.Timers.Timer
可以帮助实现周期性执行任务、在特定时间间隔后执行一次性任务以及进行精确的时间控制
Timer timer = new Timer(interval);
其中 interval 是以毫秒为单位指定的时间间隔。
设置相关属性:
timer.AutoReset=true:决定是否在每次触发事件后自动重新开始计时。如果设置为 true,则会按照时间间隔持续触发;如果设置为 false,则只触发一次。
timer.Enabled=true:控制 Timer 是否启用。
订阅 Elapsed 事件:
timer.Elapsed += OnTimedEvent;
其中 OnTimedEvent 是处理定时事件的方法。
启动 Timer:
timer.Enabled = true
踩坑:OnTimedEvent方法里开启unity的协程,不会执行协程的代码