BulletPool.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { _decorator, Component, instantiate, Node, NodePool, Pool, Prefab } from 'cc';
  2. import { resMgr } from '../../../Frames/ResourcesMgr';
  3. const { ccclass, property } = _decorator;
  4. @ccclass('BulletPool')
  5. export class BulletPool extends Component{
  6. private _bulletPrefab: Prefab = null;
  7. private _enemyBulletPrefab: Prefab = null;
  8. private _bulletPool: NodePool = new NodePool();
  9. private _enemyBulletPool: NodePool = new NodePool();
  10. init() {
  11. this._bulletPrefab = resMgr.getPrefab("Bullet");
  12. this._enemyBulletPrefab = resMgr.getPrefab("BulletEnemy");
  13. this._initPool(this._bulletPool, this._bulletPrefab, 10);
  14. this._initPool(this._enemyBulletPool, this._enemyBulletPrefab, 10);
  15. }
  16. private _initPool(pool: NodePool, prefab: Prefab, count: number) {
  17. for (let i = 0; i < count; i++) {
  18. const node = instantiate(prefab);
  19. pool.put(node);
  20. }
  21. }
  22. getBullet(isEnemy: boolean): Node {
  23. const pool = isEnemy ? this._enemyBulletPool : this._bulletPool;
  24. if(pool.size()>0){
  25. return pool.get()!;
  26. }else{
  27. //动态扩容
  28. const prefab = isEnemy ? this._enemyBulletPrefab: this._bulletPrefab;
  29. return instantiate(prefab);
  30. }
  31. }
  32. recycle(bullet: Node, isEnemy: boolean) {
  33. const pool = isEnemy ? this._enemyBulletPool : this._bulletPool;
  34. if(!pool) return;
  35. pool.put(bullet);
  36. }
  37. }