Skip to content

ECS Framework API v2.2.13


ECS Framework API / getOrAddComponent

Function: getOrAddComponent()

getOrAddComponent<T>(entity, componentType, factory): ComponentInstance<T>

Defined in: packages/core/src/ECS/TypedEntity.ts:157

获取或添加组件

如果组件已存在则返回现有组件,否则通过工厂函数创建并添加

Type Parameters

T

T extends ComponentConstructor

Parameters

entity

Entity

实体实例

componentType

T

组件类型构造函数

factory

() => ComponentInstance<T>

组件工厂函数(仅在组件不存在时调用)

Returns

ComponentInstance<T>

组件实例

Example

typescript
const health = getOrAddComponent(entity, Health, () => new Health(100));

Released under the MIT License.