PrefabManager.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. const { ccclass, property } = cc._decorator;
  2. @ccclass
  3. export default class PrefabManager {
  4. private static _prefabMap: { [key: string]: cc.Prefab } = {};
  5. private static _prefabDic: { [key: string]: cc.Node } = {};
  6. /**
  7. * 加载指定路径下的预制体
  8. * @param path 预制体的路径
  9. * @param callback 加载完成后的回调函数
  10. */
  11. public static loadPrefab(path: string, callback: (prefab: cc.Prefab) => void) {
  12. if (path in this._prefabMap) {
  13. callback(this._prefabMap[path]);
  14. } else {
  15. cc.resources.load(path, cc.Prefab, (err, prefab: cc.Prefab) => {
  16. if (err) {
  17. cc.error(err.message || err);
  18. return;
  19. }
  20. this._prefabMap[path] = prefab;
  21. callback(prefab);
  22. });
  23. }
  24. }
  25. /**
  26. * 打开指定路径下的预制体
  27. * @param path 预制体的路径
  28. * @param parentNode 预制体的父节点
  29. * @param callback 预制体加载完成后的回调函数
  30. */
  31. public static open(path: string, parentNode?: cc.Node, callback?: (node: cc.Node) => void) {
  32. // 如果已经加载过了,就直接显示
  33. if (this._prefabDic[path] != undefined) {
  34. this._prefabDic[path].active = true;
  35. } else {
  36. this.loadPrefab(path, (prefab) => {
  37. let node = cc.instantiate(prefab);
  38. if (parentNode) {
  39. node.parent = parentNode;
  40. node.setPosition(cc.v2(0, 0));
  41. this._prefabDic[path] = node;
  42. }
  43. if (callback) {
  44. callback(node);
  45. }
  46. });
  47. }
  48. }
  49. /**
  50. * 关闭指定路径下的预制体
  51. * @param path 预制体的路径
  52. * @param node 预制体的节点
  53. */
  54. public static close(node: cc.Node | string) {
  55. if ( typeof node == 'string'){
  56. this._prefabDic[node].active = false;
  57. } else if (node.isValid){
  58. node.active = false;
  59. }
  60. }
  61. /** 遍历所有 this._prefabDic里面已隐藏的节点*/
  62. public static closeAll() {
  63. // for (let key in this._prefabDic) {
  64. // if (this._prefabDic[key].active) {
  65. // this._prefabDic[key].active = false;
  66. // }
  67. // }
  68. }
  69. }