cocos3.x lua 定时器相关

在3.x lua其定时器的使用方式主要有两种:

1. 帧刷新

顾名思义,每帧都会调用,在Node及其子类中使用,无法自定义时间间隔

调用方法为:scheduleUpdateWithPriorityLua

销毁方法为:unscheduleUpdate

local function frameUpdate(dt)
    count2 = count2 + dt
    self._states[2]:setString("帧刷新时间:" .. count2)
end

--[[
self为Node相关 参数1: 回调接口用于刷新 参数2: 刷新优先级
其调用实质上就是C++中的 scheduleUpdate , 该方法会在每帧调用C++中的 update 方法 在cocoslua的NodeEx.lua中 Node.scheduleUpdate 的实现就是此方法 在销毁的时候,一定要注意调用 self:unscheduleUpdate() 方法,否则会出现问题
]] self:scheduleUpdateWithPriorityLua(frameUpdate, 0)

2. 定时器刷新

在指定的时间间隔内刷新一次或者无限次

调用方法: cc.Director:getInstance():getScheduler():scheduleScriptFunc

销毁方法: cc.Director:getInstance():getScheduler():unscheduleScriptEntry

local function timerUpdate(dt)
    count1 = count1 + dt
    self._states[1]:setString("定时刷新时间:" .. count1)
end 
--[[
参数1: 回调接口用于刷新
参数2: 每次刷新的时间间隔
参数3: 是否仅执行一次,false为无限次 (此参数若设置为 true 的话,也就是 C++中的 scheduleOnce )
]]
local _schedule = cc.Director:getInstance():getScheduler()
-- 添加判定是为了避免定时器的重复定义,销毁的时候一定要再调用一次
if self._timerScheduler ~= nil then 
    _schedule:unscheduleScriptEntry(self._timerScheduler)
    self._timerScheduler = nil 
end 
self._timerScheduler = _schedule:scheduleScriptFunc(timerUpdate, 5, false)

 

posted @ 2019-08-14 20:59  Code~  阅读(429)  评论(0)    收藏  举报