包含11節(jié)視頻教程
從零基礎(chǔ)學習unity3d游戲引擎,簡單易學的視頻教程,讓你快速掌握unity3d,并喜歡上游戲開發(fā)的樂趣。
|
在之前文章我們提到過定時器的做法《unity教程-自定義Clock定時器類 》,在平時的游戲開發(fā)過程中,我們或多或少的會用到時間類,比如技能的冷卻時間,角色的生命回復等等都會用到,而處理方式也有很多種,我們可以在每個技能上面掛載一個時間類,也可以提供一個時間管理器,來統(tǒng)一管理技能的冷卻,個人推薦第二種做法,因為這樣會更加精準! 時間管理器的類主要包括 TimerManager.cs,代碼如下: using Unity Engine; using System; using System.Collections.Generic; /// /// 移動管理 /// public class TimerManager { public static float time; public static Dictionary timerList = new Dictionary(); 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; public class TimerItem { /// /// 當前時間 /// public float currentTime; /// /// 延遲時間 /// public float delayTime; /// /// 回調(diào)函數(shù) /// 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; 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教程到此結(jié)束,下篇我們再會! 資源地址: http://cg.silucg.com/dongman/unity3d/7981.html (分享請保留) 贊0 踩0 |
未知用戶
2005-2024 朱峰社區(qū) 版權(quán)所有 遼ICP備2021001865號-1
2005-2024 ZhuFeng Community All Rights Reserved
VIP