新增identifierPool用于实体id复用

This commit is contained in:
yhh
2021-05-11 17:23:04 +08:00
parent e94b7b23e4
commit 63d307b95a
6 changed files with 65 additions and 11 deletions

View File

@@ -9,7 +9,6 @@ module es {
}
export class Entity implements IEqualityComparable {
public static _idGenerator: number = 0;
public static entityComparer: IComparer<Entity> = new EntityComparer();
/**
* 当前实体所属的场景
@@ -37,12 +36,12 @@ module es {
public updateInterval: number = 1;
public componentBits: Bits;
constructor(name: string) {
constructor(name: string, id: number) {
this.components = new ComponentList(this);
this.transform = new Transform(this);
this.componentBits = new Bits();
this.name = name;
this.id = Entity._idGenerator++;
this.id = id;
}
public _isDestroyed: boolean;
@@ -319,6 +318,7 @@ module es {
*/
public destroy() {
this._isDestroyed = true;
this.scene.identifierPool.checkIn(this.id);
this.scene.entities.remove(this);
this.transform.parent = null;

View File

@@ -13,11 +13,13 @@ module es {
public readonly entityProcessors: EntityProcessorList;
public readonly _sceneComponents: SceneComponent[] = [];
public readonly identifierPool: IdentifierPool;
private _didSceneBegin: boolean;
constructor() {
this.entities = new EntityList(this);
this.entityProcessors = new EntityProcessorList();
this.identifierPool = new IdentifierPool();
this.initialize();
}
@@ -145,7 +147,7 @@ module es {
* @param name
*/
public createEntity(name: string) {
let entity = new Entity(name);
let entity = new Entity(name, this.identifierPool.checkOut());
return this.addEntity(entity);
}

View File

@@ -0,0 +1,22 @@
module es {
export class IdentifierPool {
private ids: Bag<number>;
private nextAvailableId_ = 0;
constructor() {
this.ids = new Bag<number>();
}
public checkOut(): number {
if (this.ids.size() > 0) {
return this.ids.removeLast();
}
return this.nextAvailableId_++;
}
public checkIn(id: number): void {
this.ids.add(id);
}
}
}