56 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-12-08 21:14:02 +08:00
import Singleton from "../Base/Singleton";
import { instantiate, Node } from "cc";
import DataManager from "./DataManager";
import { EntityTypeEnum } from "../Common";
2022-12-01 22:26:41 +08:00
export default class ObjectPoolManager extends Singleton {
static get Instance() {
2022-12-08 21:14:02 +08:00
return super.GetInstance<ObjectPoolManager>();
2022-12-01 22:26:41 +08:00
}
2022-12-08 21:14:02 +08:00
private objectPool: Node = null;
private map: Map<EntityTypeEnum, Node[]> = new Map();
2022-12-01 22:26:41 +08:00
private getContainerName(objectName: EntityTypeEnum) {
2022-12-08 21:14:02 +08:00
return objectName + "Pool";
2022-12-01 22:26:41 +08:00
}
2022-12-07 22:24:46 +08:00
reset() {
2022-12-08 21:14:02 +08:00
this.objectPool = null;
this.map.clear();
2022-12-07 22:24:46 +08:00
}
2022-12-01 22:26:41 +08:00
get(objectName: EntityTypeEnum) {
if (this.objectPool === null) {
2022-12-08 21:14:02 +08:00
this.objectPool = new Node("ObjectPool");
this.objectPool.setParent(DataManager.Instance.stage);
2022-12-01 22:26:41 +08:00
}
if (!this.map.has(objectName)) {
2022-12-08 21:14:02 +08:00
this.map.set(objectName, []);
const container = new Node(this.getContainerName(objectName));
container.setParent(this.objectPool);
2022-12-01 22:26:41 +08:00
}
2022-12-08 21:14:02 +08:00
let node: Node;
const nodes = this.map.get(objectName);
2022-12-01 22:26:41 +08:00
if (!nodes.length) {
2022-12-08 21:14:02 +08:00
const prefab = DataManager.Instance.prefabMap.get(objectName);
node = instantiate(prefab);
node.name = objectName;
node.setParent(this.objectPool.getChildByName(this.getContainerName(objectName)));
2022-12-01 22:26:41 +08:00
} else {
2022-12-08 21:14:02 +08:00
node = nodes.pop();
2022-12-01 22:26:41 +08:00
}
2022-12-08 21:14:02 +08:00
node.active = true;
return node;
2022-12-01 22:26:41 +08:00
}
ret(object: Node) {
2022-12-08 21:14:02 +08:00
object.active = false;
const objectName = object.name as EntityTypeEnum;
this.map.get(objectName).push(object);
2022-12-01 22:26:41 +08:00
}
}