7月 22 2015
Unity教程之-Unity3d时间、计时管理器
在之前文章我们提到过定时器的做法《游戏简单控制逻辑Clock定时器》,在平时的游戏开发过程中,我们或多或少的会用到时间类,比如技能的冷却时间,角色的生命回复等等都会用到,而处理方式也有很多种,我们可以在每个技能上面挂载一个时间类,也可以提供一个时间管理器,来统一管理技能的冷却,个人推荐第二种做法,因为这样会更加精准!
时间管理器的类主要包括 TimerManager.cs,代码如下:
using UnityEngine; using System; using System.Collections.Generic;</p> /// <summary> /// 移动管理 /// </summary> public class TimerManager { public static float time; public static Dictionary<object, TimerItem> timerList = new Dictionary<object, TimerItem>(); public static void Run() { // 设置时间值 TimerManager.time = Time.time; TimerItem[] objectList = new TimerItem[timerList.Values.Count]; timerList.Values.CopyTo(objectList, 0); // 锁定 foreach(TimerItem timerItem in objectList) { if(timerItem != null) timerItem.Run(TimerManager.time); } } public static void Register(object objectItem, float delayTime, Action callback) { if(!timerList.ContainsKey(objectItem)) { TimerItem timerItem = new TimerItem(TimerManager.time, delayTime, callback); timerList.Add(objectItem, timerItem); } } public static void UnRegister(object objectItem) { if(timerList.ContainsKey(objectItem)) { timerList.Remove(objectItem); } } }
TimerItem.cs,代码如下:
using UnityEngine; using System;</p> public class TimerItem { /// <summary> /// 当前时间 /// </summary> public float currentTime; /// <summary> /// 延迟时间 /// </summary> public float delayTime; /// <summary> /// 回调函数 /// </summary> public Action callback; public TimerItem(float time, float delayTime, Action callback) { this.currentTime = time; this.delayTime = delayTime; this.callback = callback; } public void Run(float time) { // 计算差值 float offsetTime = time - this.currentTime; // 如果差值大等于延迟时间 if(offsetTime >= this.delayTime) { float count = offsetTime / this.delayTime - 1; float mod = offsetTime % this.delayTime; for(int index = 0; index < count; index ++) { this.callback(); } this.currentTime = time - mod; } } }
测试用例代码如下:
using UnityEngine; using System.Collections; using System.Collections.Generic;</p> public class Demo : MonoBehaviour { public GameObject roleObject; void Awake() { TimerManager.Register(this, 0.3f, ()=> { Debug.Log("0.3 -> " + System.DateTime.Now.ToString("hh:mm:ss.fff")); }); TimerManager.Register(this.gameObject, 1f, ()=> { Debug.Log("1 -> " + System.DateTime.Now.ToString("hh:mm:ss.fff")); }); } void Update() { TimerManager.Run (); } }
好了,本篇unity3d教程到此结束,下篇我们再会!