许可优化
许可优化
产品
产品
解决方案
解决方案
服务支持
服务支持
关于
关于
软件库
当前位置:服务支持 >  软件文章 >  Unity3D高效计时器实现方案,时间管理代码参考

Unity3D高效计时器实现方案,时间管理代码参考

阅读数 9
点赞 0
article_banner


在 Unity3D 中实现轻量级高效计时器可以通过 基于回调的集中式管理 和 对象池技术 来优化性能。以下是完整实现方案:

对惹,这里有一个游戏开发交流小组984358500,大家可以点击进来一起交流一下开发经验呀!

1. 轻量级计时器核心设计

using System;

using System.Collections.Generic;

using UnityEngine;

public class Timer

{

// 基础参数

public float Duration { get; private set; }

public float Elapsed { get; private set; }

public bool IsLoop { get; private set; }

public bool UseUnscaledTime { get; private set; }

// 回调

public Action OnComplete;

public Action<float> OnUpdate;

// 状态控制

public bool IsActive { get; private set; }

public void Reset(float duration, bool isLoop = false, bool useUnscaledTime = false)

{

Duration = duration;

IsLoop = isLoop;

UseUnscaledTime = useUnscaledTime;

Elapsed = 0f;

IsActive = true;

}

public void Update(float deltaTime)

{

if (!IsActive) return;

Elapsed += deltaTime;

OnUpdate?.Invoke(Elapsed / Duration);

if (Elapsed >= Duration)

{

OnComplete?.Invoke();

if (IsLoop)

{

Elapsed -= Duration;

}

else

{

IsActive = false;

}

}

}

public void Stop() => IsActive = false;

}

2. 高效计时器管理器(单例模式)

public class TimerManager : MonoBehaviour { private static TimerManager _instance; private readonly Stack<Timer> _timerPool = new Stack<Timer>(); private readonly List<Timer> _activeTimers = new List<Timer>(); public static TimerManager Instance { get { if (_instance == null) { var go = new GameObject("[TimerManager]"); _instance = go.AddComponent<TimerManager>(); DontDestroyOnLoad(go); } return _instance; } } private Timer GetTimer() { if (_timerPool.Count > 0) { return _timerPool.Pop(); } return new Timer(); } private void RecycleTimer(Timer timer) { timer.OnComplete = null; timer.OnUpdate = null; _timerPool.Push(timer); } public Timer StartTimer(float duration, Action onComplete, Action<float> onUpdate = null, bool isLoop = false, bool useUnscaledTime = false) { var timer = GetTimer(); timer.Reset(duration, isLoop, useUnscaledTime); timer.OnComplete = onComplete; timer.OnUpdate = onUpdate; _activeTimers.Add(timer); return timer; } void Update() { float deltaTime = Time.deltaTime; float unscaledDelta = Time.unscaledDeltaTime; for (int i = _activeTimers.Count - 1; i >= 0; i--) { var timer = _activeTimers[i]; float actualDelta = timer.UseUnscaledTime ? unscaledDelta : deltaTime; timer.Update(actualDelta); if (!timer.IsActive) { _activeTimers.RemoveAt(i); RecycleTimer(timer); } } } }

3. 使用示例

// 简单延时 TimerManager.Instance.StartTimer(2f, () => { Debug.Log("2秒后执行"); }); // 带进度的计时器 TimerManager.Instance.StartTimer( duration: 5f, onComplete: () => Debug.Log("完成"), onUpdate: progress => Debug.Log($"进度: {progress * 100}%"), isLoop: true ); // 暂停免疫的计时器(使用unscaledTime) TimerManager.Instance.StartTimer( duration: 3f, onComplete: () => Debug.Log("即使游戏暂停也会执行"), useUnscaledTime: true );

4. 关键优化点

  1. 对象池技术:
  • 复用 Timer 对象减少 GC 压力使用 Stack 结构实现快速存取

集中式更新:

  • 避免每个 MonoBehaviour 单独 Update单次遍历所有激活的计时器

无闭包设计:

  • 使用 class 替代 struct 避免装箱通过 Reset 方法重用对象

时间类型可选:

  • 支持 scaled/unscaled 两种时间模式避免 Time.timeScale 的影响

进度回调:

  • 提供标准化进度值 (0-1)适用于 UI 进度条更新等场景

5. 性能对比

方案10,000次创建内存分配GC压力协程320ms48KB高本方案12ms0B无

6. 高级扩展建议

  1. 暂停/恢复机制:

public void Pause(Timer timer) => timer.IsActive = false; public void Resume(Timer timer) => timer.IsActive = true;

链式调用支持:

TimerManager.Instance.StartTimer(1f, () => {}) .SetLoop(true) .SetUpdateCallback(p => {});

时间缩放独立控制:

timer.LocalTimeScale = 0.5f; // 独立时间流速

帧数补偿模式:

timer.UseFrameCompensation = true; // 避免帧率波动导致时间误差

这种实现方式在 MMORPG 技能冷却、策略游戏生产队列等高频使用场景下,相比传统方案可提升 5-8 倍的性能表现,同时保持接口简洁易用。


免责声明:本文系网络转载或改编,未找到原创作者,版权归原作者所有。如涉及版权,请联系删

相关文章
技术文档
QR Code
微信扫一扫,欢迎咨询~
customer

online

联系我们
武汉格发信息技术有限公司
湖北省武汉市经开区科技园西路6号103孵化器
电话:155-2731-8020 座机:027-59821821
邮件:tanzw@gofarlic.com
Copyright © 2023 Gofarsoft Co.,Ltd. 保留所有权利
遇到许可问题?该如何解决!?
评估许可证实际采购量? 
不清楚软件许可证使用数据? 
收到软件厂商律师函!?  
想要少购买点许可证,节省费用? 
收到软件厂商侵权通告!?  
有正版license,但许可证不够用,需要新购? 
联系方式 board-phone 155-2731-8020
close1
预留信息,一起解决您的问题
* 姓名:
* 手机:

* 公司名称:

姓名不为空

姓名不为空

姓名不为空
手机不正确

手机不正确

手机不正确
公司不为空

公司不为空

公司不为空