GameObjectPool.ts 821 B

123456789101112131415161718192021222324252627282930313233343536
  1. import { _decorator, Component, instantiate, Node, NodePool, Prefab } from 'cc';
  2. export class GameObjectPool {
  3. private _pool: NodePool;
  4. private _prefab: Prefab;
  5. constructor(prefab: Prefab, initialSize: number){
  6. this._prefab = prefab;
  7. this._pool = new NodePool();
  8. this.preLoad(initialSize);
  9. }
  10. private preLoad(count: number){
  11. for(let i = 0; i < count; i++){
  12. const node = instantiate(this._prefab);
  13. this._pool.put(node);
  14. }
  15. }
  16. //获取节点
  17. public get(): Node{
  18. let node: Node;
  19. if(this._pool.size() > 0){
  20. node = this._pool.get();
  21. } else {
  22. node = instantiate(this._prefab)
  23. }
  24. return node;
  25. }
  26. public put(node: Node){
  27. this._pool.put(node);
  28. }
  29. }