您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“Unity如何實(shí)現(xiàn)毫秒延時(shí)回調(diào)功能”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“Unity如何實(shí)現(xiàn)毫秒延時(shí)回調(diào)功能”這篇文章吧。
1: Time.deltaTime
實(shí)際上就是每幀所執(zhí)行的時(shí)間
簡單的說一下功能的實(shí)現(xiàn),下面會直接貼出源碼。
每一個(gè)新增的任務(wù)(回調(diào))都會記錄創(chuàng)建任務(wù)的時(shí)間以及延遲的時(shí)間,以及自己的事件回調(diào)。通過每幀判斷當(dāng)前幀的時(shí)間是否大于創(chuàng)建的(任務(wù)的時(shí)間+延遲的時(shí)間)
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class TickManager : MonoBehaviour { // Start is called before the first frame update public int NOW; private List<Tick> _ticks = new List<Tick>(); private void Update() { //測試--手動(dòng)創(chuàng)建一個(gè)5秒后的回調(diào) if (Input.GetKeyDown(KeyCode.A)) { Tick tick = new Tick(() => { Debug.Log("任務(wù)執(zhí)行"); },5000,NOW); _ticks.Add(tick); } //每幀所使用的毫秒時(shí)間 uint deltaTime = (uint)(Time.deltaTime * 1000); //遍歷判斷集合中的任務(wù)是否執(zhí)行 for (int i = 0; i < deltaTime; i++) { Debug.Log("幀數(shù) " + NOW); for (int j = 0; j < _ticks.Count; j++) { _ticks[j].OnTick(NOW); } ++NOW; } } class Tick { //創(chuàng)建任務(wù)的時(shí)間 public int currentTime { get; set; } //需要延遲的時(shí)間 public int delayTime { get; set; } //延遲后的回調(diào)事件 public Action action { get; set; } //構(gòu)造函數(shù)--初始化 public Tick(Action ac, int del, int now) { action = ac; delayTime = del; currentTime = now; } //判斷該任務(wù)是否執(zhí)行 public void OnTick(int now) { if (now >= (currentTime + delayTime)) { action(); } else { Debug.Log("時(shí)間還未到 "+ now); } } } }
以上是“Unity如何實(shí)現(xiàn)毫秒延時(shí)回調(diào)功能”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。