CubePool.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { _decorator, Component, instantiate, Material, Node, NodePool, Prefab, Vec3 } from 'cc';
  2. import { FrameExecute } from '../Tools/FrameExecute';
  3. const { ccclass, property } = _decorator;
  4. @ccclass('CubePool')
  5. export class CubePool {
  6. private pool: NodePool=new NodePool();
  7. private prefab: Prefab;
  8. private materials: Material[];
  9. constructor(prefab: Prefab, materials: Material[], private initialCount: number = 0) {
  10. this.prefab = prefab;
  11. this.materials = materials;
  12. this.initializePool(initialCount);
  13. }
  14. // 初始化或填充对象池
  15. private initializePool(count: number): void {
  16. FrameExecute.getInstance().execute(this.instantiateCube,this,0,count,1,{name:"cube"});
  17. }
  18. private instantiateCube()
  19. {
  20. const newCube = instantiate(this.prefab);
  21. newCube.active = false; // 初始时设置为非激活状态
  22. this.pool.put(newCube);
  23. }
  24. // 从对象池中获取一个方块
  25. public getCube(): Node {
  26. let cube = this.pool.get();
  27. if (!cube) {
  28. // 如果对象池为空,则创建新的对象并返回
  29. cube = instantiate(this.prefab);
  30. cube.active = true;
  31. } else {
  32. cube.active = true;
  33. }
  34. return cube;
  35. }
  36. // 将方块回收到对象池
  37. public recycleCube(cube: Node): void {
  38. cube.active = false; // 将方块设置为非激活状态
  39. this.pool.put(cube);
  40. }
  41. }