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