1. Update 中计算
public class TestTimer : MonoBehaviour {
private float lastTime;
private float curTime;
void Start () {
lastTime = Time.time;
}
void Update () {
curTime = Time.time;
if (curTime - lastTime >= 3)
{
Debug.Log("work");
lastTime = curTime;
}
}
}
2. 使用协程Coroutine
public class TestTimer : MonoBehaviour {
void Start () {
StartCoroutine(Do()); // 开启协程
}
IEnumerator Do()
{
yield return new WaitForSeconds(3.0f);
Debug.Log("work");
}
}
3. 使用InvokeRepeating
public class TestTimer : MonoBehaviour {
void Start () {
InvokeRepeating("Do", 3.0f, 3.0f);
// CancelInvoke("Do") // 取消定时器
}
void Do()
{
Debug.Log("work");
}
}
4. Smart Timers Manager 插件
该插件是免费插件
首先将 TimersManager 预制体拖到场景中
using UnityEngine;
using Timers;
public class NewBehaviourScript : MonoBehaviour
{
void Timer1()
{
Debug.Log("Test");
}
void ClearTimer1()
{
// 移除 Timer1
TimersManager.ClearTimer(Timer1);
}
void ForgottenTimer() {
Debug.Log("ForgottenTimer");
}
void Timer2()
{
Debug.Log("Tmer2");
}
private void Start()
{
// 每隔两秒调用 Timer1
TimersManager.SetLoopableTimer(this, 2f, Timer1);
// 5 秒后移除 Timer1 定时器
TimersManager.SetTimer(this,5f,ClearTimer1);
// 每隔一秒调用一次,总共调用 50 次
TimersManager.SetTimer(this, 1f, 50, ForgottenTimer);
// 打印总共需要的秒数
Debug.Log("Remaining time :" +
TimersManager.RemainingTime(ForgottenTimer) + "Sec"
);
// 10 秒后删除
TimersManager.SetTimer(this, 10f, delegate { Destroy(this); });
//
// 每秒调用,无限次
Timer t1 = new Timer(1f, Timer.INFINITE, Timer2);
TimersManager.SetTimer(this, t1);
}
}
GUI 调用
using UnityEngine;
using System.Collections.Generic;
using Timers;
public class GUI_TimersList : MonoBehaviour
{
public List<Timer> Timers = new List<Timer>();
protected virtual void Start()
{
TimersManager.AddTimers(this, Timers);
}
}
5. UniRx 定时
Observable.Timer(TimeSpan.FromSeconds(2.0f)).Subscribe(_ =>
{
Debug.Log("延时两秒");
}).AddTo(this);
//两个参数
Observable.Timer(TimeSpan.FromSeconds(2))
.Subscribe(_ => print("2秒到" + Time.time),
() =>
{
print("On完成" + Time.time);//和上上面这个委托同时完成
});