天天看点

CocosCreator异步加载资源方法资源加载封装使用

资源加载封装

import { Asset, AssetManager, dragonBones, ImageAsset, JsonAsset, resources, _decorator } from "cc";
import { LogData } from "../log/LogData";

/** 
 * 资源加载api封装
 */
const { ccclass, property } = _decorator;
export class loadRes{

    /**  动态加载资源,可以带回调函数 ,返回promise对象
    *  @param url resources文件路径
    * @param type 资源类型
    * @param callback 回调函数
    */
    public static load_res(url:string,type:any,callback?: { (value: any): void; (value: any): void; (arg0: any): void; }){
        return new Promise((resolve, reject) => {
            resources.load(url, type,(err, res:any) => {
                if (err) {
                    reject(err);
                } else {
                    if(callback){
                        callback(res);
                    }
                    resolve(res);
                }
            });
        })
    }

}
           

可以传入回调函数,方便给外面的变量赋值。

使用

使用异步函数按顺序加载,避免回调地狱。

async func() { 
        await loadRes.load_res(url,type,(value:any)=>{
            console.log(value);
            this.变量 = value;
        });
}
           

继续阅读