wave6-ecs-state-machine-design
Choose the correct ECS state representation — enum field, IEnableableComponent, or structural add/remove — based on transition frequency, state count, and query-filtering requirements.
- License 许可
- MIT
- 最近更新
- 2026-07-25
- Stars
- ★ 8
- Forks
- 0
01 前言 Front Matter
- name
- wave6-ecs-state-machine-design
- tags
- [ "enableable", "state-machine" ]
- metadata
- { "tier": 3, "internal-only": true }
- description
- Choose the correct ECS state representation — enum field, IEnableableComponent, or structural add/remove — based on transition frequency, state count, and query-filtering requirements.
03 SKILL.md 正文
ECS State Machine Design — Decision Model
Intent
Choose the correct ECS state representation — enum field, IEnableableComponent, or structural add/remove — based on transition frequency, state count, and query-filtering requirements.
Decision Model
| Criterion | Enum Field | IEnableableComponent | Structural Add/Remove |
|---|---|---|---|
| State count | 3+ exclusive states | Exactly 2 (active/inactive) | Any; data ownership varies |
| Transition frequency | Any | High (per-frame) | Low (lifecycle) |
| Downstream query filter | No (branch in system) | Yes (automatic at query level) | Yes (archetype-level) |
| Memory when inactive | Always present | Always present | Freed |
| Cost per transition | Field write (cheapest) | Bit flip (O(1)) | Chunk move (10-100x) |
Senior Pattern — Enum FSM
public enum BotState { MoveToTarget, Attack, Retreat, Idle, Dead }
public struct BotAI : IComponentData
{
public BotState State;
public float StateTimer;
}
[BurstCompile]
public partial struct BotFSMJob : IJobEntity
{
public float DeltaTime;
[BurstCompile]
public void Execute(ref BotAI bot, ref LocalTransform t)
{
switch (bot.State)
{
case BotState.MoveToTarget:
bot.StateTimer -= DeltaTime;
if (bot.StateTimer <= 0) bot.State = BotState.Attack;
break;
case BotState.Attack:
// attack logic
break;
// ...
}
}
}
Senior Pattern — Enableable Binary Flag
// Zero-size component — just the enabled bit matters:
public struct Stealth : IComponentData, IEnableableComponent { }
// Systems automatically see only active entities:
new StealthBehaviorJob().ScheduleParallel(state.Dependency); // only enabled
new StealthRevealJob().ScheduleParallel(state.Dependency); // only enabled
// Mixed: enum for internal FSM, enableable for external visibility:
public struct EnemyAI : IComponentData { public EnemyState State; }
public struct DetectedByPlayer : IComponentData, IEnableableComponent { }
// Internal transitions via enum field; player detection via enableable
Senior Pattern — Structural (Lifecycle)
// Spawn → Active (ECB adds components once):
ecb.AddComponent<EnemyAI>(entity, new EnemyAI { State = EnemyState.Patrol });
ecb.AddComponent<PhysicsVelocity>(entity, default);
// Death (ECB removes components once — entity enters cleanup archetype):
ecb.RemoveComponent<EnemyAI>(entity);
ecb.AddComponent<DeadTag>(entity);
Anti-Patterns
- Structural AddComponent/RemoveComponent for per-frame transitions — 10-100x more expensive than enum write or bit flip; causes archetype churn.
- IEnableableComponent for 3+ exclusive states — no query can express "exactly state X of N"; use enum.
- Enum fields when downstream systems need to query-filter automatically — requires branch inside every system; enableable components filter at chunk level.
- Creating a separate entity per state — unnecessary structural complexity; prefer enum or enableable on the same entity.
Performance Benchmark (from ECS StateChange sample)
- Enum field write: fastest for single-entity per-frame transitions
- Enableable bit flip: fastest for bulk query-filtered transitions (no chunk move)
- Structural change: 10-100x slower; reserve for entity lifecycle only
Architecture Guidance
- Mixed approach is valid and common: enum for internal FSM state, IEnableableComponent for external visibility/behavior flags.
- Document state ownership: which system writes state, which systems read it.
- For 2-state binary: prefer IEnableableComponent when downstream systems should auto-filter; prefer enum field when only one system cares.
Related Skills
[[enableable-component]], [[wave6-enabled-ref-rw-in-job]], [[wave6-with-disabled-query-filter]], [[structural-change-cost-model]], [[icleanupcomponentdata-runtime]]
04 同仓库更多 Skills
dots-update-groups
How to choose the right ECS system group and ordering so per-frame and per-fixed-step work is deterministic and never races its own readers. Covers InitializationSystemGroup / SimulationSystemGroup / PresentationSystemGroup / FixedStepSimulationSystemGroup / VariableRateSimulationSystemGroup, UpdateBefore / UpdateAfter peer ordering, OrderFirst / OrderLast group-boundary placement, RateManager, and the cross-group ordering trap. Use when adding an ISystem, fixing "value visible one frame late" bugs, or coupling simulation to a fixed timestep.
dots-transform-patterns
The Entities 1.x transform model — LocalTransform (writable input) vs LocalToWorld (system-owned matrix), Parent/Child hierarchy, reparenting cost, uniform vs non-uniform scale (PostTransformMatrix), and when to opt out with custom transform systems. Use when designing parent/child hierarchies, runtime reparenting (mount/dismount/socket), or choosing transform components at the Baker boundary.
dots-singleton-patterns
Model cross-system shared configuration and game state as a single-entity component with a strict single-writer contract. Covers RequireForUpdate gating, SystemAPI.GetSingleton / GetSingletonRW / HasSingleton / TryGetSingleton, bake-time vs runtime-created vs ECB-system singletons, the "exactly one entity" runtime invariant, and the single-writer rule. Use when designing frame-stable global config, shared mutable state, or any component intended to exist on exactly one entity.
dots-hybrid-bridge
The one-way bridge between DOTS-owned runtime state and Unity-owned presentation. Covers UnityObjectRef for managed asset refs in components, the DOTS-writes / Unity-reads ownership rule, when to use managed IComponentData vs UnityObjectRef vs CompanionComponent, baker-bridge vs runtime-bridge, and SubScene boundary rules. Use when an entity must reference Unity assets (Mesh, Material, AudioClip, ScriptableObject), a MonoBehaviour view must read entity state, or input/UI must trigger ECS work.
dots-event-driven-ecs
Model one-frame events and external requests in ECS without dual ownership, polling, or persistent state leaks. Covers request-tag pattern with ECB, enableable command components (no structural change), event buffers (IBufferElementData), explicit consumer ownership, one-frame latency rules, and the banned C# event / UnityEvent / static bus anti-patterns. Use when input/UI/network must trigger ECS work, when a one-frame signal fans out to N consumers (damage, hit, collision), or when state changes must be processed exactly once.
valid_skill
A complete, well-formed test fixture skill for SkillHub validation testing. Covers basic task routing and code review for Unity projects.