class Timer
Description
A simple and efficient timer class.
Syntax is close to JavaScript.
Note that direct calls do not need to be attached to the scene.
The current timer program runs the true Time for the game unaffected by time.timescale
精度对比
Dotween的定时器运行情况 - 实际上现在网上大部分的定时器都是这样的情况不够精确只能保证秒级相似 然后下一秒补偿 不能保证帧级的精准度
而优化的Timer和Unity自带的Invoke 是帧级别的精度
用法
````
private void Start()
{
Timer.SetTimeout( 2f, () =>
{
Debug.Log( "Delay Call" );
} );
Timer.SetInterval( 1f, () =>
{
Debug.Log( "Call per Second" );
} );
Timer.SetInterval( 0f, () =>
{
//call for pre frames
//listen any key event
if( Input.anyKey )
{
// listen mouseButton Event
if ( Input.GetMouseButtonDown( 0 ) )
{
Debug.Log( "hello Timer." );
}
if( Input.GetKeyDown( KeyCode.Space ) )
{
Debug.Log( "Clean self all generate time." );
Timer.ClearTimer( this );
}
}
} );
}
功能 | 支持 |
---|---|
调度任务对象自动回收 | True |
单次延迟调用 | True |
循环定时调度 | True |
可通过对象来清理所有定时器 | True |
进入后台暂停定时器 | True (可以通过修改 m_isBackground 来开关) |
是否有多个线上项目磨练 | 目前有四个线上项目运行 无异常情况 |
源码
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
///
/// Timer 轻量高效定时器
///
/// 当前定时器程序为游戏运行真实时间
/// 内置对象池Task回收
/// 已及更方便灵活的调用方式
///
/// Anchor: ChenJC
/// Time: 2022/10/09
/// 原文: https://blog.csdn.net/qq_39162566/article/details/113105351
/// </summary>
public class Timer : MonoBehaviour
{
//定时器数据类
public class TimerTask
{
public ulong ID;
public float lifeCycle;
public float expirationTime;
public long times;
public Action func;
//你可以通过此方法来获取定时器的运行进度 0 ~ 1 1.0表示即将要调用func
//你可以通过 GetTimer( id ) 获取当前Task的Clone体
public float progress
{
get
{
return 1.0f - Mathf.Clamp01( ( expirationTime - Time.time ) / lifeCycle );
}
}
//获取一个当前TimerTask的副本出来
public TimerTask Clone()
{
var timerTask = new TimerTask();
timerTask.ID = ID;
timerTask.expirationTime = expirationTime;
timerTask.lifeCycle = lifeCycle;
timerTask.times = times;
timerTask.func = func;
return timerTask;
}
//释放回收当前定时器
public void Destory()
{
freeTaskCls.Enqueue( this );
}
//重置
public void Reset()
{
expirationTime = Time.time + lifeCycle;
}
}
#region Member property
protected static List<TimerTask> activeTaskCls = new List<TimerTask>();//激活中的TimerTask对象
protected static Queue<TimerTask> freeTaskCls = new Queue<TimerTask>();//闲置TimerTask对象
protected static HashSet<Action> lateChannel = new HashSet<Action>();//确保callLate调用的唯一性
protected static ulong idOffset