
---- -- 时间任务模块支持单次、多次、无限次、暂停、恢复、停止、多实例 ---- local Timer {} Timer.__index Timer ---- -- 所有运行中的计时器全局管理 ---- local TimerList {} ---- -- 创建一个计时器 -- delay: 延迟时间秒 -- func: 回调函数 -- count: 执行次数-1无限次1一次n多次 ---- function Timer.new(delay, func, count) local self setmetatable({}, Timer) ---- -- 基础配置 ---- self.delay delay or 1 self.func func or function() end self.totalCount count or 1 ---- -- 运行状态 ---- self.running false self.paused false self.currentCount 0 self.timer 0 ---- -- 加入列表 ---- table.insert(TimerList, self) return self end ---- -- 启动计时器 ---- function Timer:Start() self.running true self.paused false self.timer 0 return self end function Timer:RunImmediately() if self.func then pcall(self.func) end ---- -- 重置计时避免连续触发 ---- self.timer 0 return self end ---- -- 暂停计时器 ---- function Timer:Pause() self.paused true return self end ---- -- 恢复计时器 ---- function Timer:Resume() self.paused false return self end ---- -- 停止计时器 ---- function Timer:Stop() self.running false self.paused false self.func nil end ---- -- 每帧更新全局调用一次 ---- function Timer.Update(dt) for i #TimerList, 1, -1 do local t TimerList[i] ---- -- 已停止 / 暂停 → 跳过 ---- if not t.running or t.paused then goto continue end t.timer t.timer dt if t.timer t.delay then t.timer 0 t.currentCount t.currentCount 1 ---- -- 执行回调 ---- if t.func then pcall(t.func) end ---- -- 判断是否停止 ---- if t.totalCount ~ -1 and t.currentCount t.totalCount then t:Stop() table.remove(TimerList, i) end end ::continue:: end end ---- -- 停止所有计时器 ---- function Timer.ClearAll() for _, t in ipairs(TimerList) do t:Stop() end TimerList {} end return Timer使用方法挂载全局函数并在Update传入当前游戏帧率每帧约0.016_G.Timer require(Timer.lua) --在引擎更新处只更新调用这一次 Timer.Update(dt) --其他地方需要用则 local timedemo Timer.new(1, function() --运行函数 end, 1) timedemo:Start() --[[ 三个参数第一个是多少时间运行一次单位秒可以写 0.5 则是半秒 第二个参数是触发函数就是时间运行时触发的 第三个是运行多少次填几久是运行几次-1 表示无限次 --]]