PoolManager.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { _decorator, Component, Node, Prefab } from 'cc';
  2. import { GameObjectPool } from './GameObjectPool';
  3. export class PoolManager {
  4. private static _instance: PoolManager;
  5. private _pools: Map<string, GameObjectPool> = new Map();
  6. public static get instance(){
  7. if(!this._instance){
  8. this._instance = new PoolManager();
  9. }
  10. return this._instance;
  11. }
  12. public registerPool(prefab: Prefab, initialSize: number = 10){
  13. const key = prefab.name;
  14. if(!this._pools.has(key)){
  15. this._pools.set(key, new GameObjectPool(prefab, initialSize));
  16. }
  17. }
  18. //获取节点实例
  19. public get(prefab: Prefab): Node{
  20. const key = prefab.name;
  21. if(!this._pools.has(key)){
  22. this.registerPool(prefab);
  23. }
  24. return this._pools.get(key)!.get();
  25. }
  26. //回收节点
  27. public put(node: Node){
  28. const key = node.name;
  29. if(this._pools.has(key)){
  30. this._pools.get(key)!.put(node);
  31. } else {
  32. Error("PoolManager destroy")
  33. node.destroy();
  34. }
  35. }
  36. }