42 lines
1.3 KiB
Markdown
42 lines
1.3 KiB
Markdown
# GameObject::GetComponent
|
|
|
|
返回当前对象自身上的第一个匹配组件。
|
|
|
|
该方法当前提供两个公开重载:
|
|
|
|
```cpp
|
|
template<typename T> T* GetComponent();
|
|
template<typename T> const T* GetComponent() const;
|
|
```
|
|
|
|
## 搜索顺序
|
|
|
|
两个重载的搜索顺序一致:
|
|
|
|
1. 先尝试把内建 `m_transform` `dynamic_cast` 成 `T`
|
|
2. 再按 `m_components` 当前顺序逐个 `dynamic_cast`
|
|
3. 返回第一个命中的组件
|
|
4. 全部没命中时返回 `nullptr`
|
|
|
|
## 当前语义边界
|
|
|
|
- 只搜索“当前对象自身”,不会递归到父节点或子节点
|
|
- `TransformComponent` 是特例:虽然它不在 `m_components` 中,但这里仍可能最先返回它
|
|
- 对普通组件来说,多个同类型组件时只返回第一个匹配项
|
|
|
|
这也意味着像 `GetComponent<Component>()` 这种宽类型查询,当前很可能先拿到 `TransformComponent`,因为它会在普通组件之前被检查。
|
|
|
|
## 测试锚点
|
|
|
|
`tests/Components/test_game_object.cpp` 当前验证了:
|
|
|
|
- 添加后的普通组件可以被 `GetComponent<T>()` 找回
|
|
- 不存在目标类型时返回 `nullptr`
|
|
|
|
## 相关文档
|
|
|
|
- [GetComponents](GetComponents.md)
|
|
- [GetComponentInChildren](GetComponentInChildren.md)
|
|
- [GetComponentInParent](GetComponentInParent.md)
|
|
- [GetTransform](GetTransform.md)
|