Files
XCEngine/docs/api/components/component/component.md

70 lines
2.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Component
**命名空间**: `XCEngine::Components`
**类型**: `class (abstract)`
**头文件**: `XCEngine/Components/Component.h`
**描述**: ECS 组件基类,定义所有组件的公共接口和生命周期。
## 概述
Component 是 XCEngine ECS 架构中的组件基类,所有具体组件(如 TransformComponent、AudioSourceComponent都继承自此类。它定义了组件的通用生命周期方法Awake、Start、Update、OnEnable、OnDisable、OnDestroy以及获取所属 GameObject 和场景的接口。组件通过友元类 GameObject 自动管理其所属游戏对象。
## 公共方法
| 方法 | 描述 |
|------|------|
| [`GetName`](get-name.md) | 获取组件名称(纯虚函数) |
| [`GetGameObject`](get-game-object.md) | 获取所属 GameObject |
| [`transform`](transform.md) | 获取变换组件引用 |
| [`GetScene`](get-scene.md) | 获取所属场景 |
| [`IsEnabled`](is-enabled.md) | 检查组件是否启用 |
| [`SetEnabled`](set-enabled.md) | 设置组件启用状态 |
## 虚方法(生命周期)
| 方法 | 描述 |
|------|------|
| `virtual void Awake()` | 组件创建后首次启用时调用 |
| `virtual void Start()` | 在首次更新前调用 |
| `virtual void Update(float deltaTime)` | 每帧更新 |
| `virtual void FixedUpdate()` | 固定频率更新(物理) |
| `virtual void LateUpdate(float deltaTime)` | 晚于 Update 更新 |
| `virtual void OnEnable()` | 启用时调用 |
| `virtual void OnDisable()` | 禁用时调用 |
| `virtual void OnDestroy()` | 销毁时调用 |
| `virtual void Serialize(std::ostream& os) const` | 序列化组件数据 |
| `virtual void Deserialize(std::istream& is)` | 反序列化组件数据 |
## 使用示例
```cpp
#include <XCEngine/Components/Component.h>
#include <XCEngine/Components/GameObject.h>
using namespace XCEngine::Components;
class MyComponent : public Component {
public:
void Awake() override {
printf("Awake: %s\n", GetName().c_str());
}
void Update(float deltaTime) override {
// 每帧逻辑
}
std::string GetName() const override {
return "MyComponent";
}
};
```
## 相关文档
- [Components 模块总览](../components.md) - Components 模块总览
- [GameObject](../game-object/game-object.md) - 游戏对象
- [TransformComponent](../transform-component/transform-component.md) - 变换组件