Slash-The-Hordes/assets/Scripts/Services/ObjectPool.ts

86 lines
2.5 KiB
TypeScript
Raw Permalink Normal View History

import { Component, instantiate, Node, Prefab } from "cc";
export class ObjectPool<T extends Component> {
private prefab: Prefab;
private parent: Node;
private pooledObjects: PooledObject<T>[] = [];
2022-11-16 11:26:20 +00:00
private componentName: string;
2022-11-16 11:26:20 +00:00
public constructor(prefab: Prefab, parent: Node, defaultPoolCount: number, componentName: string) {
this.prefab = prefab;
this.parent = parent;
2022-11-16 11:26:20 +00:00
this.componentName = componentName;
for (let i = 0; i < defaultPoolCount; i++) {
2023-01-06 11:32:54 +00:00
this.createNew();
}
}
public borrow(): T {
const objectToBorrow: PooledObject<T> | null = this.pooledObjects.find((o) => !o.IsBorrowed);
if (objectToBorrow != null) {
return objectToBorrow.borrow();
}
return this.createNew().borrow();
}
public return(object: T): void {
const objectToReturn: PooledObject<T> | null = this.pooledObjects.find((o) => o.Equals(object));
if (objectToReturn == null) {
throw new Error("Object " + this.prefab.name + " is not a member of the pool");
}
objectToReturn.return();
}
private createNew(): PooledObject<T> {
2022-11-16 11:26:20 +00:00
const newPooledObject: PooledObject<T> = new PooledObject(this.prefab, this.parent, this.componentName);
this.pooledObjects.push(newPooledObject);
return newPooledObject;
}
}
class PooledObject<T extends Component> {
private isBorrowed = false;
private defaultParent: Node;
private instancedNode: Node;
private instancedComponent: T;
2022-11-16 11:26:20 +00:00
public constructor(prefab: Prefab, defaultParent: Node, componentName: string) {
this.defaultParent = defaultParent;
this.instancedNode = instantiate(prefab);
2022-11-16 11:26:20 +00:00
this.instancedComponent = <T>this.instancedNode.getComponent(componentName);
if (this.instancedComponent == null) {
2023-01-06 11:33:55 +00:00
console.error("Object " + prefab.name + " does not have component " + componentName);
}
this.clear();
}
public get IsBorrowed(): boolean {
return this.isBorrowed;
}
public Equals(component: T): boolean {
return this.instancedComponent == component;
}
public borrow(): T {
this.isBorrowed = true;
return this.instancedComponent;
}
public return(): void {
this.clear();
}
private clear(): void {
this.instancedNode.active = false;
this.instancedNode.parent = this.defaultParent;
this.isBorrowed = false;
}
}