关于cocos2dx for lua资源加载优化方案

之前我写游戏加载都是从一个json文件写入要加载的文件名来实现加载,但是如果资源

比较多的情况下,会导致非常难管理,需要逐个写入。所以换了另外一种方式来加载文件。

首先,我是通过场景之前的切换时候,加载下一个场景的资源,避免一次加载导致内存占

用过大,所以,我将各个场景中的资源分开单独的文件夹,如果两个或多个场景有共用的

资源可以再开多一个共用的文件夹,两个场景切换的时候都加载。然后一个场景中的文件夹

下再细分成不同类型资源的文件夹,比如spine动画文件夹,spriteframe文件夹,texture

文件夹等等,遍历各个类型文件夹的资源,通过不同加载方法加载。总结来说必须要分类好

资源,不然后续进行更新资源包会特别难管理。

lua遍历目录文件夹下的方法如下:

  local cmd = "ls "..cc.FileUtils:getInstance():getWritablePath().."res/spine"--存放spine动画的路径,ls是输出目录文件的命令

    

    local s = io.popen(cmd)

    local fileLists = s:read("*all")--读取该路径中的所有spine动画,返回一个字符串

    local strTbl = lua_string_split(fileLists," ")--分割字符串

    

    for k,v in ipairs(strTbl) do

        local sprite = sp.SkeletonAnimation:create(string.format("spine/%s/%s.json",v,v),string.format("spine/%s/%s.atlas",v,v),0.2)

        layer:addChild(sprite)

    end

--分割字符串函数

function cc.exports.lua_string_split(str, split_char)      

    local sub_str_tab = {};  

    while (true) do          

        local pos = string.find(str, split_char);    

        if (not pos) then              

            break;    

        end  

        local sub_str = string.sub(str, 1, pos - 1);                

        local size_t = table.getn(sub_str_tab)  

        table.insert(sub_str_tab,size_t+1,sub_str);  

        local t = string.len(str);  

        str = string.sub(str, pos + 1, t);     

    end      

    return sub_str_tab;  

end

转载请注明出处,from 博客园HemJohn

原文地址:https://www.cnblogs.com/HemJohn/p/4972648.html