游戏系统组件组装——组件怎么组装成完整游戏
一句话
游戏组件的组装方式有三种:ECS(数据驱动)、GameObject 模式(对象挂载)、纯数据驱动(配置生成)。组装决定「创建 Entity、添加 Component、System 自动处理」还是「创建 GameObject、挂载 Component」——组装权决定控制权。
一、三种组装方式
组装方式 1:ECS(Entity-Component-System)
1 2 3 4
| Entity = 玩家/敌人/道具 的 ID Component = 位置/血量/攻击力 的数据 System = 移动系统/战斗系统/渲染系统 的逻辑 组装 = 创建 Entity,添加 Component,System 自动处理
|
玩家例子:
1 2 3 4 5
| Entity 100 + TransformComponent(position, rotation) + SpriteComponent(texture) + HealthComponent(hp) + WeaponComponent(weapon)
|
然后系统处理:
1 2 3
| MovementSystem → 读取 Transform + Velocity → 修改位置 RenderSystem → 读取 Transform + Sprite → 绘制 CombatSystem → 读取 Weapon + Health → 计算伤害
|
组装方式 2:GameObject 模式(Unity/Unreal 风格)
1 2 3
| GameObject = 玩家/敌人/道具 Component = MonoBehaviour/ActorComponent 组装 = 创建 GameObject,挂载 Component
|
组装方式 3:纯数据驱动
1 2
| 配置文件定义 Entity 和 Component 引擎读取配置,自动创建和组装
|
二、传统 OOP vs ECS
1 2 3 4 5
| class Player { position; hp; speed; move(); attack(); draw(); };
|
1 2 3 4 5 6
| // ECS PlayerEntity ← 只有一个 ID + TransformComponent + SpriteComponent + HealthComponent + WeaponComponent
|
1 2 3
| MovementSystem → 读取 Transform + Velocity → 修改位置 RenderSystem → 读取 Transform + Sprite → 绘制 CombatSystem → 读取 Weapon + Health → 计算伤害
|
三、谁来组装:GameApplication
1 2 3 4 5 6 7 8 9 10 11
| int main() { GameApplication app; app.run(); }
class GameApplication { void run() { Engine engine; Game game; game.registerComponents(engine); game.registerSystems(engine); engine.run(); } };
|
Game 把组件和系统注册进 Engine,Engine 的 Scheduler 负责运行:
1 2 3 4
| engine.addSystem<PlayerSystem>(); engine.addSystem<CombatSystem>(); engine.addSystem<EnemySystem>(); engine.run();
|
完整组装:
1
| GameApplication → Engine → Scheduler → Game Systems → ECS World → Game Components
|
四、需要回答的问题
- ECS vs GameObject vs 数据驱动,各自适合什么场景?
- ECS:大量实体、结构在运行时会变(RTS 单位、弹幕、塔防)、需要数据局部性
- GameObject:结构固定、对象职责清晰、继承天然(Unity/Unreal 主流)
- 数据驱动:关卡/内容由策划配置、需要热更新、运行时加载
- 组件的生命周期管理: 创建、初始化、销毁的顺序——谁负责创建、谁负责销毁、生命周期谁持有
- 组件之间的异常怎么传播?——System 抛错谁处理?AI 寻路失败、存档损坏怎么恢复?
五、游戏业务的再框架化
如果游戏很复杂,还可以继续分层:
1 2 3 4 5
| Engine ↓ Game Framework(RPG Framework:Character/Inventory/Quest/Combat/Save) ↓ 具体 RPG(魔法/武器/敌人/具体任务)
|
下层框架提供运行和组装能力,上层框架利用下层框架再次进行领域组装。 ECS Engine 是支撑;Game 是业务;Scheduler 是 Engine 提供的运行机制;Game Systems 是业务逻辑;GameApplication 是把 Engine 和 Game 组装起来的应用层。
与其他线的关系
- 与引擎组装线:本线的组装发生在 Engine 提供的运行机制(Scheduler)之上
- 与游戏系统组件线:本线回答「组件怎么拼」,组件线回答「有什么组件」
- 与 ECS 与注册机制线(拆解与组织 04):ECS 的注册机制(registerComponent/addSystem → Scheduler 调度)就是运行时可扩展的核心——本线讲三种组装方式怎么选,04 讲 ECS 的注册机制本身
- 与拆解与组织主题:三种组装方式是「组织」在游戏层的三种选择——组织方式由结构变化频率决定
- 与接口与注入线:Game 向 Engine 注册组件/系统,本质是依赖注入——Game 不持有 Engine 的具体实现,而是把自己注册进 Engine 的接口