unity/creator 通过名称直接加载资源
问题:无论是unity及cocos creator,提供的资源加载方案都是在resource下通过资源路径进行加载,这样我们在加载资源时,可能面临一个很尴尬的问题就是,这个url可能是一个很长的字符串,经常有人人为的填写失误造成加载资源错误。
解决方案:将资源的名称和路径写入配置表中,通过资源名称直接得到路径,并加载资源
以下以cocos为例,将cocos中asset/resource下的所有资源,建立一个一一对应的资源路径表,python文件暂命名为resConfigTool.py,bat文件就不多说了。
步骤1:通过python一键将所有的资源写入表中,resConfigTool.py中代码如下:
import os
basePath = ".\\assets\\resources"
outFile = ".\\assets\\Script\\System\\ConfigPath.ts"
fileCategorys = [".png", ".PNG", ".jpg", ".mp3", ".wav", ".prefab", ".anim"]
lines = []
def makeResDict():
print("Read Name And Path Start!")
for (path, dirs, files) in os.walk(basePath):
for filename in files:
if filename.find(".meta") != -1:
continue
resName = ""
for oneCategory in fileCategorys:
if filename.find(oneCategory) != -1:
nameArr = filename.split(".")
resName = nameArr[0]
break
if resName == "":
continue
#startIndex = path.index(".") + 7
resPath = path.replace("\\", "/")
resPath = resPath.replace("./assets/resources/", "")
resPath = resPath + "/" + resName
line = "\t" + resName + " : \"" + resPath + "\",\n"
if line in lines:
print("Read Name And Path Error!, res name repeat! >>>" + resName)
return False
lines.append(line)
print("Read Name And Path Success!")
return True
def writeFile():
print("Write Name And Path Start!")
dst = open(outFile, 'w', encoding='utf-8')
dst.write("export let ConfigPath = {\n")
for line in lines:
dst.write(line)
print(line)
dst.write("}")
print("Write Name And Path Success!")
dst.close()
def main():
isOk = makeResDict()
if isOk:
lines.sort()
writeFile()
os.system('pause & exit')
if __name__ == '__main__':
main()
步骤2:双击resConfigTool.bat,生成如下图的文件,这就是资源所在目录
示例3:加载->如下,提供得到资源路径的方法GetResPath,
提供加载资源的方法Load
这样就可以直接通过资源名加载资源了
private GetResPath(resName: string) {
if (!ConfigPath.hasOwnProperty(resName)) {
Log.Error("AssetManager res is not exist " + resName);
return "";
}
return ConfigPath[resName];
}
public Load(resName: string, callback: Function, type?: typeof cc.Asset) {
let path = this.GetResPath(resName);
if (IsNullOrEmpty(path)) {
callback(null);
return;
}
//1.直接获取
let res1 = cc.loader.getRes(path, type);
if (res1 != null) {
callback(res1);
return;
}
//2.再尝试加载
cc.loader.loadRes(path, type, (err, res2) => {
if (err == null) {
callback(res2);
return;
}
Log.Error("AssetManager Load ,path="+path+',err=' + err.message || err);
callback(null);
});
}
小结:管理资源时,不要有相同的资源名称,这也是作为一个项目管理应该避免的事情,如果出现同名资源,该方案也无效了。
讨论为很多种管理资源的方案,建议不要随便乱命名资源,最好作到分文件夹,分门别类的作好资源管理