PrefabPool.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { Node,NodePool, Prefab, instantiate} from "cc";
  2. /** node对象池 */
  3. class PrefabPool {
  4. private _pools:Map<string,NodePool>= new Map();
  5. private _node:Node;
  6. constructor(){
  7. if(this._node==null){
  8. this._node=new Node();
  9. this._node.active=false;
  10. }
  11. }
  12. private getPool(path:string):NodePool{
  13. let pool= this._pools.get(path);
  14. if(pool==null){
  15. pool= new NodePool();
  16. this._pools.set(path,pool);
  17. }
  18. return pool;
  19. }
  20. public GetNode(p:Prefab):Node{
  21. let pool= this.getPool(p.name);
  22. let node = pool.get();
  23. if (!node){
  24. node = instantiate (p);
  25. node.name=p.name;
  26. }
  27. return node;
  28. }
  29. public RecNode(node:Node):void{
  30. node.parent=this._node;
  31. this.getPool(node.name).put(node);
  32. }
  33. public InitPool(p:Prefab,n:number=10):void{
  34. let pool= this.getPool(p.name);
  35. for(let i=0;i<n;i++){
  36. let node = instantiate (p);
  37. node.name=p.name;
  38. node.parent=this._node;
  39. pool.put(node);
  40. }
  41. }
  42. public Clear():void{
  43. if(!this._node)return;
  44. this._node.removeAllChildren();
  45. this._pools.forEach((v,k)=>{
  46. v.clear();
  47. })
  48. this._pools.clear();
  49. }
  50. public getAllPoolNames(): string[] {
  51. return Object.keys(this._pools);
  52. }
  53. public getPoolSize(poolName: string): number {
  54. const pool = this._pools[poolName];
  55. if (pool) {
  56. return pool.size();
  57. }
  58. return 0;
  59. }
  60. }
  61. export default function get_new_prefab_pool():PrefabPool { return new PrefabPool();}