严格输入/输出定义
// AI模块公共接口
public interface IAIModule {
void SetNavigationTarget(Entity entity, Vector3 target);
PathResult GetCurrentPath(Entity entity);
}
事件驱动通信
// 物理模块发出的事件
public struct CollisionEvent : IComponentData {
public Entity EntityA;
public Entity EntityB;
public float3 ImpactForce;
}
// 库存模块监听事件
world.GetOrCreateSystem<InventorySystem>()
.RegisterEvent<CollisionEvent>(OnCollision);
public class ModuleRegistry {
private Dictionary<Type, IGameModule> _modules = new();
public T GetModule<T>() where T : IGameModule {
return (T)_modules[typeof(T)];
}
public void RegisterModule(IGameModule module) {
_modules.Add(module.GetType(), module);
}
}
// 初始化时注册
var registry = new ModuleRegistry();
registry.RegisterModule(new AIModule());
registry.RegisterModule(new PhysicsModule());
显式依赖声明
public class InventoryModule : IGameModule {
[ModuleDependency]
public PhysicsModule Physics { get; set; }
}
循环依赖检测
void ValidateDependencies() {
var graph = new DependencyGraph();
foreach(var module in _modules.Values) {
graph.AddNode(module.GetType());
foreach(var dep in module.GetDependencies()) {
graph.AddEdge(module.GetType(), dep);
}
}
if(graph.HasCycle())
throw new CyclicDependencyException();
}
模块内内存池
public class PhysicsModule {
private CollisionEventPool _eventPool = new(1024);
void Simulate() {
var evt = _eventPool.Get();
// ... 填充事件数据
_eventSystem.Dispatch(evt);
}
}
批处理接口
public interface IBatchPhysicsQuery {
void RaycastBatch(RaycastQuery[] queries);
}
AI模块调用物理模块
public class PathfindingSystem : SystemBase {
private PhysicsModule _physics;
protected override void OnUpdate() {
_physics = World.GetModule<PhysicsModule>();
Entities.ForEach((ref PathData path) => {
// 批量查询导航网格
var queries = new NativeArray<RaycastQuery>(10, Allocator.Temp);
_physics.RaycastBatch(queries); // 跨模块调用
}).ScheduleParallel();
}
}
状态序列化接口
public interface IHotReloadable {
byte[] CaptureState();
void RestoreState(byte[] state);
}
热交换流程
操作 | 直接访问耗时 | 模块化访问耗时 | 开销比 |
---|---|---|---|
单组件获取 | 0.02ms | 0.03ms | +50% |
跨模块批处理(1000次) | 1.2ms | 1.3ms | +8.3% |
测试环境:Ryzen 9 5900X, 50000实体 |
终极方案:核心引擎保持扁平ECS结构,游戏逻辑层采用模块化封装,平衡性能与可维护性