Lua遅延機能、タイマー



Lua Delay Function Timer



アイデア

Unityコルーチン効果の関数をluaで記述したい場合は、トリガーするまでN秒遅らせます。どうしようもなく、Luaはパッケージ化された関数呼び出しを提供しません。
最初のアイデアは、luaコルーチンを使用してスレッド内のスリープなどのメソッドを呼び出すことでした。以前にAndroid開発を行ったときも同様のアイデアを使用しました。
その結果、Baiduは円を描き、インターネットで睡眠の効果を達成する方法は4つあります。
https://blog.csdn.net/charlie_2010/article/details/6719891から4つのメソッドが再現されています
方法1

--Set an exit condition in an infinite loop, but this approach will consume a lot of CPU resources, it is strongly not recommended to use function sleep(n) local t0 = os.clock() while os.clock() - t0 <= n do end end

方法2



--Set an exit condition in an infinite loop, but this approach will consume a lot of CPU resources, it is strongly not recommended to use function sleep(n) os.execute('sleep ' .. n) end

方法3

--Although Windows does not have a built-in sleep command, we can take advantage of the nature of the ping command function sleep(n) if n > 0 then os.execute('ping -n ' .. tonumber(n + 1) .. ' localhost > NUL') end end

方法4



--Using the select function in the socket library, you can pass 0.1 to n, so that the sleep time accuracy reaches the millisecond level. require('socket') function sleep(n) socket.select(nil, nil, n) end

要約すると、メソッド1は消費量が多すぎ、メソッド2、メソッド3は使用できず、メソッド4が呼び出された後、socket.select()でスタックし、結果が得られません。
最終的には、Unityエンジンの更新ライフサイクルの助けを借りて達成されます。
1.モジュールをカプセル化して、遅延タスクを記録し、タスクをサイクルします
2. Unityを使用して、モジュールのUpdateインターフェイスを呼び出し、Lua内部タイマーを実装します

コード

Timer ={ timerTasks={}--Delayed task timerLoopTasks={}--Delayed loop task } --Set delay loop function id, initial delay, interval delay after loop, loop time, loop function, callback function at the end function Timer:SetDelayLoopFunction(id, delayTime, delayTime1, loopTime, funcLoop,funcOnFinish) if self.timerLoopTasks[id] == nil then self.timerLoopTasks[id] = {} end self.timerLoopTasks[id].startTime=CS.UnityEngine.Time.time+delayTime--trigger timing self.timerLoopTasks[id].loopDelay=delayTime1--the interval of each loop self.timerLoopTasks[id].overTime=CS.UnityEngine.Time.time+loopTime--loop duration self.timerLoopTasks[id].funcLoop=funcLoop--loop function self.timerLoopTasks[id].funcOnFinish=funcOnFinish--callback function at the end end --Delay function id, delay time, trigger method function Timer:SetDelayFunction(id, delayTime, func) if self.timerTasks[id] == nil then self.timerTasks[id] = {} end self.timerTasks[id].func = func self.timerTasks[id].startTime = CS.UnityEngine.Time.time + delayTime end --Update function Timer:Update() for k, v in pairs(self.timerTasks) do --Meet the delay condition trigger if v.startTime

効果、

画像
画像