| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- import { _decorator, Component, instantiate, Material, Node, NodePool, Prefab, Vec3 } from 'cc';
- import { FrameExecute } from '../Tools/FrameExecute';
- const { ccclass, property } = _decorator;
- @ccclass('CubePool')
- export class CubePool {
- private pool: NodePool=new NodePool();
- private prefab: Prefab;
- private materials: Material[];
- constructor(prefab: Prefab, materials: Material[], private initialCount: number = 0) {
- this.prefab = prefab;
- this.materials = materials;
- this.initializePool(initialCount);
- }
- // 初始化或填充对象池
- private initializePool(count: number): void {
- FrameExecute.getInstance().execute(this.instantiateCube,this,0,count,1,{name:"cube"});
- }
- private instantiateCube()
- {
- const newCube = instantiate(this.prefab);
- newCube.active = false; // 初始时设置为非激活状态
- this.pool.put(newCube);
- }
- // 从对象池中获取一个方块
- public getCube(): Node {
- let cube = this.pool.get();
- if (!cube) {
- // 如果对象池为空,则创建新的对象并返回
- cube = instantiate(this.prefab);
- cube.active = true;
- } else {
- cube.active = true;
- }
- return cube;
- }
- // 将方块回收到对象池
- public recycleCube(cube: Node): void {
- cube.active = false; // 将方块设置为非激活状态
- this.pool.put(cube);
- }
- }
|