Files
XCEngine/docs/api/XCEngine/Components/GameObject/AddComponent.md

45 lines
1.1 KiB
Markdown
Raw Normal View History

2026-03-26 16:45:24 +08:00
# GameObject::AddComponent
2026-04-03 16:11:48 +08:00
为当前对象添加一个普通组件,或返回已有的内建 `Transform`
2026-03-26 16:45:24 +08:00
```cpp
2026-04-03 16:11:48 +08:00
template<typename T, typename... Args>
T* AddComponent(Args&&... args);
2026-03-26 16:45:24 +08:00
```
2026-04-03 16:11:48 +08:00
## 行为说明
2026-03-26 16:45:24 +08:00
2026-04-03 16:11:48 +08:00
当前模板实现分两条路径:
2026-03-26 16:45:24 +08:00
2026-04-03 16:11:48 +08:00
- 如果 `T` 继承自 `TransformComponent`
- 直接返回已有 `m_transform`
- 不会创建第二个 `Transform`
- 否则
- 构造一个新的组件实例
- 回填 `component->m_gameObject = this`
- 放入 `m_components`
- 返回新组件指针
2026-03-26 16:45:24 +08:00
2026-04-03 16:11:48 +08:00
## 当前不会自动发生什么
2026-03-26 16:45:24 +08:00
2026-04-03 16:11:48 +08:00
运行时添加普通组件时,当前实现**不会自动补发**
2026-03-26 16:45:24 +08:00
2026-04-03 16:11:48 +08:00
- `Awake()`
- `Start()`
- `OnEnable()`
这是当前对象系统最重要的现实边界之一。组件挂载完成,不等于它已经追平生命周期进度。
## 所有权语义
- 普通组件的所有权由 `GameObject` 内部 `std::unique_ptr<Component>` 接管
- 返回值只是观察指针
- 调用方不应自行 `delete`
2026-03-26 16:45:24 +08:00
## 相关文档
2026-04-03 16:11:48 +08:00
- [GameObject](GameObject.md)
- [GetComponent](GetComponent.md)
- [RemoveComponent](RemoveComponent.md)
- [GetTransform](GetTransform.md)