关于异步加载资源同步写法,在一个帖子直接抄了一份过来
想起了一句话 “没啥不是加一层封装不能解决的”
`
export class ResLoader {
/**
* 载入单个资源
* - 输出log
* @todo ts的类型系统(特别是泛型这一块)需要进一步学习,争取去掉强制类型转换
* @param path
* @param type
* @static
*/
static LoadRes(path: string, type: T): Promise<InstanceType> {
return new Promise(res => {
cc.loader.loadRes(path, type, (err, resource) => {
if (err) {
res(null)
} else {
res(resource)
}
})
})
}
/**
* 载入dir资源
* - 输出log
* @param path
* @param type
* @static
*/
static loadResDir<T extends typeof cc.Asset>(path: string, type: T): Promise<InstanceType<T>[]> {
return new Promise(res => {
cc.loader.loadResDir(path, type, (err, resource) => {
if (err) {
res(null)
} else {
res(resource)
}
})
})
}
}
`
用法:
async Init() { let prefab = await ResLoader.LoadRes('Prefabs/Game/TilePrefab', cc.Prefab) }