* @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)
| 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 获取指定类型的组件 |
no test coverage detected