pool_manager.ts 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. const { ccclass, property } = cc._decorator;
  2. @ccclass
  3. export default class pool_manager {
  4. pools: any = {};
  5. resKey: any = {};
  6. init(callback, res: cc.Prefab) {
  7. // 初始化资源键值对
  8. this.initializeResKey(res);
  9. // 预创建并回收指定数量的节点到对象池
  10. this.preCreateAndRecoverNodes(res);
  11. // 执行回调函数(如果存在)
  12. this.executeCallback(callback);
  13. }
  14. // 初始化资源键值对的函数,将特定资源与对应的键关联起来
  15. private initializeResKey(res: cc.Prefab): void {
  16. this.resKey['TileBlock'] = res;
  17. }
  18. // 预创建并回收指定数量的节点到对象池的函数
  19. private preCreateAndRecoverNodes(res: cc.Prefab): void {
  20. for (let i = 0; i < 100; i++) {
  21. let node = cc.instantiate(res);
  22. this.recover('TileBlock', node);
  23. }
  24. }
  25. // 执行回调函数(如果存在)的函数
  26. private executeCallback(callback: () => void): void {
  27. callback && callback();
  28. }
  29. get(key: string) {
  30. // 获取指定键对应的节点池,如果不存在则创建一个新的节点池
  31. this.createNodePoolIfNotExists(key);
  32. // 尝试从节点池中获取节点,如果能获取到则返回其组件
  33. let node = this.tryGetNodeFromPool(key);
  34. if (node) {
  35. return node.getComponent(node.name);
  36. }
  37. // 如果节点池为空,创建一个新的节点并返回其组件
  38. node = this.createNewNode(key);
  39. return node.getComponent(node.name);
  40. }
  41. // 获取指定键对应的节点池,如果不存在则创建一个新的节点池的函数
  42. private createNodePoolIfNotExists(key: string): void {
  43. if (this.pools[key] == null) {
  44. this.pools[key] = new cc.NodePool();
  45. }
  46. }
  47. // 尝试从节点池中获取节点,如果能获取到则返回其组件的函数
  48. private tryGetNodeFromPool(key: string): cc.Node | null {
  49. if (this.pools[key].size() > 0) {
  50. let node = this.pools[key].get();
  51. return node;
  52. }
  53. return null;
  54. }
  55. // 如果节点池为空,创建一个新的节点并返回其组件的函数
  56. private createNewNode(key: string): cc.Node {
  57. let node = cc.instantiate(this.resKey[key]);
  58. return node;
  59. }
  60. recover(key: string, node: cc.Node) {
  61. // 获取指定键对应的节点池,如果不存在则创建一个新的节点池
  62. this.createNodePoolIfNotExists(key);
  63. // 将节点放入对应的节点池中
  64. this.putNodeIntoPool(key, node);
  65. }
  66. // 获取指定键对应的节点池,如果不存在则创建一个新的节点池的函数(与前面重复定义,可考虑提取为公共函数)
  67. private createNodePoolIfNotExistsForRecover(key: string): void {
  68. if (this.pools[key] == null) {
  69. this.pools[key] = new cc.NodePool();
  70. }
  71. }
  72. // 将节点放入对应的节点池中
  73. private putNodeIntoPool(key: string, node: cc.Node): void {
  74. this.pools[key].put(node);
  75. }
  76. }