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

42 lines
1.3 KiB
Markdown
Raw Normal View History

2026-03-26 16:45:24 +08:00
# GameObject::GetComponent
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
```cpp
template<typename T> T* GetComponent();
2026-04-03 16:11:48 +08:00
template<typename T> const T* GetComponent() const;
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
1. 先尝试把内建 `m_transform` `dynamic_cast``T`
2. 再按 `m_components` 当前顺序逐个 `dynamic_cast`
3. 返回第一个命中的组件
4. 全部没命中时返回 `nullptr`
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
- 只搜索“当前对象自身”,不会递归到父节点或子节点
- `TransformComponent` 是特例:虽然它不在 `m_components` 中,但这里仍可能最先返回它
- 对普通组件来说,多个同类型组件时只返回第一个匹配项
2026-03-26 16:45:24 +08:00
2026-04-03 16:11:48 +08:00
这也意味着像 `GetComponent<Component>()` 这种宽类型查询,当前很可能先拿到 `TransformComponent`,因为它会在普通组件之前被检查。
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
`tests/Components/test_game_object.cpp` 当前验证了:
2026-03-26 16:45:24 +08:00
2026-04-03 16:11:48 +08:00
- 添加后的普通组件可以被 `GetComponent<T>()` 找回
- 不存在目标类型时返回 `nullptr`
2026-03-26 16:45:24 +08:00
## 相关文档
2026-04-03 16:11:48 +08:00
- [GetComponents](GetComponents.md)
- [GetComponentInChildren](GetComponentInChildren.md)
- [GetComponentInParent](GetComponentInParent.md)
- [GetTransform](GetTransform.md)