const { ccclass, property } = cc._decorator; @ccclass export default class PrefabManager { private static _prefabMap: { [key: string]: cc.Prefab } = {}; private static _prefabDic: { [key: string]: cc.Node } = {}; /** * 加载指定路径下的预制体 * @param path 预制体的路径 * @param callback 加载完成后的回调函数 */ public static loadPrefab(path: string, callback: (prefab: cc.Prefab) => void) { if (path in this._prefabMap) { callback(this._prefabMap[path]); } else { cc.resources.load(path, cc.Prefab, (err, prefab: cc.Prefab) => { if (err) { cc.error(err.message || err); return; } this._prefabMap[path] = prefab; callback(prefab); }); } } /** * 打开指定路径下的预制体 * @param path 预制体的路径 * @param parentNode 预制体的父节点 * @param callback 预制体加载完成后的回调函数 */ public static open(path: string, parentNode?: cc.Node, callback?: (node: cc.Node) => void) { // 如果已经加载过了,就直接显示 if (this._prefabDic[path] != undefined) { this._prefabDic[path].active = true; } else { this.loadPrefab(path, (prefab) => { let node = cc.instantiate(prefab); if (parentNode) { node.parent = parentNode; node.setPosition(cc.v2(0, 0)); this._prefabDic[path] = node; } if (callback) { callback(node); } }); } } /** * 关闭指定路径下的预制体 * @param path 预制体的路径 * @param node 预制体的节点 */ public static close(node: cc.Node | string) { if ( typeof node == 'string'){ this._prefabDic[node].active = false; } else if (node.isValid){ node.active = false; } } /** 遍历所有 this._prefabDic里面已隐藏的节点*/ public static closeAll() { // for (let key in this._prefabDic) { // if (this._prefabDic[key].active) { // this._prefabDic[key].active = false; // } // } } }