poolManager.ts 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. import { _decorator, Prefab, Node, instantiate, NodePool } from "cc";
  2. const { ccclass, property } = _decorator;
  3. @ccclass("poolManager")
  4. export class poolManager {
  5. /* class member could be defined like this */
  6. // dummy = '';
  7. /* use `property` decorator if your want the member to be serializable */
  8. // @property
  9. // serializableDummy = 0;
  10. private _dictPool: any = {}
  11. private _dictPrefab: any = {}
  12. static _instance: poolManager;
  13. /* class member could be defined like this */
  14. // dummy = '';
  15. /* use `property` decorator if your want the member to be serializable */
  16. // @property
  17. // serializableDummy = 0;
  18. static get instance() {
  19. if (this._instance) {
  20. return this._instance;
  21. }
  22. this._instance = new poolManager();
  23. return this._instance;
  24. }
  25. /**
  26. * 根据预设从对象池中获取对应节点
  27. */
  28. public getNode(prefab: Prefab, parent: Node) {
  29. let name = prefab.name;
  30. //@ts-ignore
  31. if (!prefab.position) {
  32. //@ts-ignore
  33. name = prefab.data.name;
  34. }
  35. this._dictPrefab[name] = prefab;
  36. let node = null;
  37. if (this._dictPool.hasOwnProperty(name)) {
  38. //已有对应的对象池
  39. let pool = this._dictPool[name];
  40. if (pool.size() > 0) {
  41. node = pool.get();
  42. } else {
  43. node = instantiate(prefab);
  44. }
  45. } else {
  46. //没有对应对象池,创建他!
  47. let pool = new NodePool();
  48. this._dictPool[name] = pool;
  49. node = instantiate(prefab);
  50. }
  51. node.parent = parent;
  52. node.active = true;
  53. return node;
  54. }
  55. /**
  56. * 将对应节点放回对象池中
  57. */
  58. public putNode(node: Node) {
  59. if (!node) {
  60. return;
  61. }
  62. let name = node.name;
  63. let pool = null;
  64. if (this._dictPool.hasOwnProperty(name)) {
  65. //已有对应的对象池
  66. pool = this._dictPool[name];
  67. } else {
  68. //没有对应对象池,创建他!
  69. pool = new NodePool();
  70. this._dictPool[name] = pool;
  71. }
  72. pool.put(node);
  73. }
  74. /**
  75. * 根据名称,清除对应对象池
  76. */
  77. public clearPool(name: string) {
  78. if (this._dictPool.hasOwnProperty(name)) {
  79. let pool = this._dictPool[name];
  80. pool.clear();
  81. }
  82. }
  83. /**
  84. * 预生成对象池
  85. * @param prefab
  86. * @param nodeNum
  87. * 使用——poolManager.instance.prePool(prefab, 40);
  88. */
  89. public prePool(prefab: Prefab, nodeNum: number) {
  90. const name = prefab.name;
  91. let pool = new NodePool();
  92. this._dictPool[name] = pool;
  93. for (let i = 0; i < nodeNum; i++) {
  94. const node = instantiate(prefab);
  95. pool.put(node);
  96. }
  97. }
  98. }