ECSComponentPool.ts 1022 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. /** @format */
  2. import {ComPoolIndex} from './Const'
  3. import {ECSTypedComConstructor} from './ECSComponent'
  4. /**
  5. * 组件池
  6. */
  7. export class ECSComponentPool<T> {
  8. private _componentConstructor: ECSTypedComConstructor<T>
  9. public constructor(comCons: ECSTypedComConstructor<T>) {
  10. this._componentConstructor = comCons
  11. }
  12. private _components: T[] = [] // components
  13. private _reservedIdxs: ComPoolIndex[] = [] // 缓存的component idx
  14. public get(idx: ComPoolIndex): T {
  15. return this._components[idx]
  16. }
  17. public alloc(): ComPoolIndex {
  18. if (this._reservedIdxs.length > 0) {
  19. let ret = this._reservedIdxs.pop()
  20. this._componentConstructor.apply(this._components[ret]) // 重置对象
  21. return ret
  22. }
  23. let newInstance = new this._componentConstructor()
  24. this._components.push(newInstance)
  25. return this._components.length - 1
  26. }
  27. public free(idx: ComPoolIndex) {
  28. this._reservedIdxs.push(idx)
  29. }
  30. }