ResUtils.ts 2.59 KB
export namespace ResUtils {
    export async function loadRes<T extends cc.Asset>(resource: string, type: new () => T, maxTryCount = 3): Promise<T> {
        return new Promise((resolve, reject) => {
            let tryCount = 0;
            function loadFunc() {
                tryCount++;
                cc.resources.load(resource, type as any, (err: Error, res: any) => {
                    if (err) {
                        if (tryCount < maxTryCount) {
                            setTimeout(() => {
                                loadFunc();
                            }, 500);
                        } else {
                            reject(err);
                        }
                    } else {
                        if (res.json) {
                            resolve(res.json);
                        } else if (res.text) {
                            resolve(res.text);
                        } else {
                            resolve(res);
                        }
                    }
                });
            }
            loadFunc();
        });
    }

    //动态加载图片的方法
    export async function loadOnlineImg(container: cc.Sprite, url: string): Promise<any> {
        return new Promise<any>((resolve, reject) => {
            cc.assetManager.loadRemote(url, function (err, texture) {
                if (err) {
                    reject(err)
                } else {
                    var sprite = new cc.SpriteFrame(texture);
                    container.spriteFrame = sprite;
                    resolve()
                }
            });

        })
    }

    /**释放资源 */
    export function releaseRes(resource: string) {
        cc.resources.release(resource)
    }
    /**批量释放资源 */
    export function releaseResArray(resources: string[]) {
        for (let i = 0; i < resources.length; i++) {
            cc.resources.release(resources[i])
        }
    }

    export function releaseAsset(asset: cc.Asset) {
        cc.assetManager.releaseAsset(asset)
    }

    export function releaseAssetArray(assets: cc.Asset[]) {
        assets.forEach((asset) => cc.assetManager.releaseAsset(asset));
    }

    /**加载预制体并实例化node */
    export async function createWithPrefab(resource: string): Promise<cc.Node> {
        let prefab = await ResUtils.loadRes<cc.Prefab>(resource, cc.Prefab);
        if (!prefab) throw new Error("Load prefab failed!");
        let node = cc.instantiate(prefab);
        if (node) {
            return node;
        } else {
            throw new Error("Instantiate node failed!");
        }
    }

    //检
}