MCPcopy Create free account
hub / github.com/esengine/esengine / addComponent

Method addComponent

packages/core/src/ECS/Entity.ts:454–499  ·  view source on GitHub ↗

* @zh 添加组件到实体 * @en Add component to entity * * @param component - @zh 要添加的组件实例 @en Component instance to add * @returns @zh 添加的组件实例 @en Added component instance * @throws @zh 如果实体已存在该类型的组件 @en If entity already has this component type * * @example * ```typesc

(component: T)

Source from the content-addressed store, hash-verified

452 * ```
453 */
454 public addComponent<T extends Component>(component: T): T {
455 const componentType = component.constructor as ComponentType<T>;
456
457 if (!this.scene) {
458 throw new Error(
459 'Entity must be added to Scene before adding components. Use scene.createEntity() instead of new Entity()'
460 );
461 }
462
463 if (!this.scene.componentStorageManager) {
464 throw new Error('Scene does not have componentStorageManager');
465 }
466
467 if (this.hasComponent(componentType)) {
468 throw new Error(`Entity ${this.name} already has component ${getComponentTypeName(componentType)}`);
469 }
470
471 this.addComponentInternal(component);
472
473 this.scene.componentStorageManager.addComponent(this.id, component);
474
475 component.entityId = this.id;
476 this.scene.referenceTracker?.registerEntityScene(this.id, this.scene);
477
478 if (this.scene.isEditorMode) {
479 this.scene.queueDeferredComponentCallback(() => component.onAddedToEntity());
480 } else {
481 component.onAddedToEntity();
482 }
483
484 if (this.scene.eventSystem) {
485 this.scene.eventSystem.emitSync('component:added', {
486 timestamp: Date.now(),
487 source: 'Entity',
488 entityId: this.id,
489 entityName: this.name,
490 entityTag: this.tag?.toString(),
491 componentType: getComponentTypeName(componentType),
492 component: component
493 });
494 }
495
496 this.notifyQuerySystems(componentType);
497
498 return component;
499 }
500
501 /**
502 * @zh 获取指定类型的组件

Callers 15

createComponentMethod · 0.95
addComponentsMethod · 0.95
deserializeMethod · 0.95
startMethod · 0.45
_spawnEffectMethod · 0.45
SceneHierarchyFunction · 0.45
ViewportFunction · 0.45
createSpriteEntityMethod · 0.45
undoMethod · 0.45
executeMethod · 0.45

Calls 10

hasComponentMethod · 0.95
addComponentInternalMethod · 0.95
notifyQuerySystemsMethod · 0.95
registerEntitySceneMethod · 0.80
nowMethod · 0.80
getComponentTypeNameFunction · 0.50
onAddedToEntityMethod · 0.45
emitSyncMethod · 0.45
toStringMethod · 0.45

Tested by

no test coverage detected