Lua 搭配Unity实现简单计时器

注意:这里是无法直接运行使用的,需要搭配具体的项目框架,在Unity的Update中每帧调用。

(这里主要只是提供大概代码和思路)

这里使用的UnityEngine.Time.deltaTime,其实就是Unity中的Time.deltaTime

TimeSystem.lua

--class为之前写的面向对象类
TimeSystem = class()

--单例
TimeSystem.Instance = function()
        if (TimeSystem.m_instance == nil) then
                TimeSystem.m_instance = TimeSystem.new();
        end
        return TimeSystem.m_instance
end

function TimeSystem:ctor()
        self.tempTime = 0
        
        --事件池
        self.TimerDict = {}
        self.timerIndex = 1
end


--参数:时间间隔、循环几次、回调函数、回调对象、回调参数
function TimeSystem:AddTimer(delta,loopTimes,callBack,obj,param)
        if callBack==nil then
                return
        end
        
        self.TimerDict[self.timerIndex] = {leftTime = delta,delta = delta,loopTimes = loopTimes,callBack = callBack,obj = obj,param = param,timerIndex = self.timerIndex}
        self.timerIndex = self.timerIndex + 1;
        
        return self.timerIndex - 1
end

function TimeSystem:RemoveTimer(timerIndex)
        if timerIndex==nil then
                return
        end
        self.TimerDict[timerIndex] = nil
end

--让这个函数被Unity的Update每帧调用
--timeInterval:时间间隔
--每帧都调用函数,但不是每帧都遍历一次字典,不然太耗性能
--可以设置为0.1,一般延迟调用时间也不会太短
function TimeSystem:Update(timeInterval)
        
        self.tempTime = self.tempTime + UnityEngine.Time.deltaTime;
        
        if self.tempTime < timeInterval then
                return
        else
                self.tempTime = 0
        end
        
        --遍历字典,更新剩余时间,时间到了就执行函数
        for k,v in pairs(self.TimerDict) do
                v.leftTime = v.leftTime - timeInterval
                
                if v.leftTime <= 0 then
                        if v.obj ~= nil then
                                if v.callBack then
                                        v.callBack(v.obj,v.param)
                                end
                        else
                                if v.callBack then
                                        v.callBack(v.param)
                                end
                        end

                        v.loopTimes = v.loopTimes - 1
                        v.leftTime = v.delta
                        
                        if v.loopTimes <= 0 then
                                v.callBack = nil
                                self:RemoveTimer(v.timerIndex)
                        end
                end
        end
end

function TimeSystem:Clear()
        self.TimerDict = {}
end

Test.lua

--每隔1.5s执行一次输出,总共执行两次
TimeSystem.GetInstance():AddTimer(1.5,2,
        function()
                print("在时间" .. os.time() .."执行了")
        end
,self
);