今天主要在迁移过程中主要碰到了加载资源的异步问题,就做了一个异步加载图集的工具,代码如下:
// 从 “…/…/config/System” 导入 System 模块
import { System } from "../../config/System";
/** 加载图集管理程序 */
export class chessAtlas {
// 图集是否已经加载的标志
private static atlasPieceLoaded: boolean = false;
// 图集对象
private static atlas_pieces: cc.SpriteAtlas = null;
// 加载图集的异步函数
public static async loadAtlasPieces(): Promise<cc.SpriteAtlas> {
// 返回一个 Promise 对象,这个 Promise 对象将会包含 cc.SpriteAtlas 对象
return new Promise<cc.SpriteAtlas>((resolve, reject) => {
// 如果图集已经加载过,直接将图集对象传入 resolve
if (chessAtlas.atlasPieceLoaded) {
resolve(chessAtlas.atlas_pieces);
// 如果图集没有加载过,调用 cc.loader.loadRes() 加载图集资源
} else {
cc.loader.loadRes(System.getAtlas_pieces(), cc.SpriteAtlas, (err, atlas) => {
// 如果加载资源失败,将错误对象传入 reject
if (err) {
reject(err);
// 如果加载资源成功,将图集对象存储在 chessAtlas 中,并将图集对象传入 resolve
} else {
chessAtlas.atlasPieceLoaded = true;
chessAtlas.atlas_pieces = atlas;
resolve(atlas);
}
});
}
});
}
}
调用时就比较简单,当然也是异步的
/** 刷新显示吃掉的棋子 */
public async showKill(): Promise<void> {
if (!this.cell) return;
if (!this.curplayerData) return;
let type = this.curplayerData.type == "w" ? "b" : "w";
this.cell.removeAllChildren();
let i: number = 0;
this.curplayerData.kills.forEach(async (k: D_PiecesBase) => {
let ui: cc.Node = new cc.Node();
const atlas: cc.SpriteAtlas = await chessAtlas.loadAtlasPieces();
let uiFrame = atlas.getSpriteFrame(System.getPieces(type, k.nice, true));
ui.addComponent(cc.Sprite).spriteFrame = uiFrame;
let gw: number = 30;
let bitH: number = 30;
let l: number = gw / bitH;
let w: number = ui.width * l;
let h: number = ui.height * l;
ui.scale = l;
ui.x = gw * 0.7 * i + (gw - w) / 2;
ui.y = gw / 2 + gw - h - 1;
i++;
this.cell.addChild(ui);
});
}
核心调用代码为:
const atlas: cc.SpriteAtlas = await chessAtlas.loadAtlasPieces();
let uiFrame = atlas.getSpriteFrame(System.getPieces(type, k.nice, true));
ui.addComponent(cc.Sprite).spriteFrame = uiFrame;