cocos2dx-lua资源预加载的优化

前言说明:

cocos2dx-lua的资源加载也可以进行异步加载,往往加载资源时会造成内存急剧上升,对应应用内存不足时的机子容易使程序闪退,下面介绍种策略,稳定的加载资源:即延时加载,且在每隔几帧时加载一次资源,就会使资源加载平滑很多。上示例代码:

-------------------------------请注意,代码开始了------------------------------

--假如有以下文件需要预加载
local PLIST_FILE = {
    "resource/bg/Plist_bg" , 
    "resource/btns/Plist_btns" , 
    "resource/img/Plist_img" , 
    "resource/ui/Plist_ui",
    
    "res/anima/Plist_anima_aaa",
    "res/anima/Plist_anima_bbb",
    "res/anima/Plist_anima_ccc",
    "res/anima/Plist_anima_ddd",
    "res/anima/Plist_anima_eee",
    "res/anima/Plist_anima_fff",
    "res/anima/Plist_anima_ggg",
    "res/anima/Plist_anima_hhh"
}

function LoadingLayer:updateLoadRes()
    self.loadResNum = 0

    local updateTimes = 0
    local nowLoadNums = 0
    local function updateLoad(dt)
        updateTimes = updateTimes + 1
        if updateTimes > 20 and updateTimes % 3 == 0 then  --延迟20帧,并且每3帧加载下一个资源
            nowLoadNums = nowLoadNums + 1
            display.loadImage(PLIST_FILE[nowLoadNums]..".png", handler(self, self.loadResCallBack))

            if #PLIST_FILE <= nowLoadNums then
                print(" -- > stop update load res ... ")
                self:closeSchedule(self.scheduleListener)
            end
        end
    end
    self.scheduleListener = cc.Director:getInstance():getScheduler():scheduleScriptFunc(updateLoad , 0 , false)
end

function LoadingLayer:closeSchedule(scheduleTag)
    if scheduleTag ~= nil then
        cc.Director:getInstance():getScheduler():unscheduleScriptEntry(scheduleTag)
        scheduleTag = nil
    end
end

function LoadingLayer:loadResCallBack(texture2d)
    self.loadResNum = self.loadResNum + 1
    local plistName = PLIST_FILE[self.loadResNum]..".plist"
    --加载plist文件
    cc.SpriteFrameCache:getInstance():addSpriteFrames(plistName)
    print(" -- > load res callback plist : " , plistName , self.loadResNum)
    local nowPercent = math.min(100, 100*(self.loadResNum/#PLIST_FILE))
    self.loadingBar:setPercent(nowPercent)  --如果有进度条,更新百分比
    if self.loadResNum >= #PLIST_FILE then
        --TODO load finished do your game action
        --资源全部加载完成,进行你的操作
    end
end

-------------------------------代码结束------------------------------

猜你喜欢

转载自blog.csdn.net/jshmachine/article/details/81705105