wave5-stateful-physics-event-buffers
Detect Enter, Stay, and Exit states for trigger and collision events using Unity Physics''s built-in stateful event buffer systems, which maintain per-entity DynamicBuffer<StatefulTriggerEvent>.
- License 许可
- MIT
- 最近更新
- 2026-07-25
- Stars
- ★ 8
- Forks
- 0
01 前言 Front Matter
- name
- wave5-stateful-physics-event-buffers
- tags
- [ "physics" ]
- metadata
- { "tier": 3, "internal-only": true }
- description
- Detect Enter, Stay, and Exit states for trigger and collision events using Unity Physics''s built-in stateful event buffer systems, which maintain per-entity DynamicBuffer<StatefulTriggerEvent>.
03 SKILL.md 正文
Stateful Physics Event Buffers
Intent
Detect Enter, Stay, and Exit states for trigger and collision events using Unity Physics's built-in stateful event buffer systems, which maintain per-entity DynamicBuffer<StatefulTriggerEvent>.
Use When
- Trigger zones (enter/exit): pickups, portals, damage volumes
- Collision events with Enter/Stay/Exit semantics: landing detection, impact response
Avoid When
- Only "something is overlapping this frame" is needed — use SimulationSingleton.ScheduleCallbacks directly (cheaper, stateless)
- Event count is very high (>10,000/frame) — the clear+collect+convert chain adds per-frame overhead
Setup Requirements
- Add StatefulTriggerEventBufferAuthoring component to entities needing trigger event tracking.
- Set PhysicsShapeAuthoring Collision Response = "Raise Trigger Events" on the trigger collider.
- Unity Physics includes StatefulTriggerEventBufferSystem and StatefulCollisionEventBufferSystem built-in.
Senior Pattern
[UpdateInGroup(typeof(FixedStepSimulationSystemGroup))]
[UpdateAfter(typeof(StatefulTriggerEventBufferSystem))]
[BurstCompile]
public partial struct TriggerZoneSystem : ISystem
{
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
state.Dependency = new ProcessTriggerJob().ScheduleParallel(state.Dependency);
}
}
[BurstCompile]
public partial struct ProcessTriggerJob : IJobEntity
{
[BurstCompile]
public void Execute(ref TriggerZoneState zone,
in DynamicBuffer<StatefulTriggerEvent> events)
{
for (int i = 0; i < events.Length; i++)
{
switch (events[i].State)
{
case StatefulEventState.Enter: zone.EnteredCount++; break;
case StatefulEventState.Exit: zone.EnteredCount--; break;
// StatefulEventState.Stay: fires every frame overlap persists — handle if needed
}
}
}
}
Event states:
- StatefulEventState.Enter — first frame of overlap
- StatefulEventState.Stay — overlap continues (fires every frame)
- StatefulEventState.Exit — first frame overlap ends
Anti-Patterns
- Reading DynamicBuffer<StatefulTriggerEvent> before StatefulTriggerEventBufferSystem runs — empty buffer; always [UpdateAfter(StatefulTriggerEventBufferSystem)].
- Forgetting StatefulTriggerEventBufferAuthoring — no buffer is created; events silently dropped.
- Not filtering by ev.State == Enter — Stay events fire every frame overlap persists; unguarded code fires every frame.
- Accessing buffer elements across frames — buffer is cleared and rebuilt every fixed tick.
Runtime Risks
- Buffer cleared every fixed tick — do not cache references to buffer elements across frames.
- StatefulTriggerEventExclude component on an entity suppresses event collection — use for performance optimization on high-frequency entities that don't need state tracking.
- Both entities in a trigger pair receive events — guard against double-processing in symmetric handlers.
Performance Notes
- Clear is parallel; collection and conversion are sequential — three-job chain per fixed tick.
- Group trigger-zone entities in same archetype for buffer cache locality.
- For very high event counts, prefer stateless SimulationSingleton.ScheduleCallbacks.
Architecture Guidance
- Event detection: FixedStepSimulationSystemGroup [UpdateAfter(StatefulTriggerEventBufferSystem)].
- Gameplay responses (VFX, audio via hybrid bridge): SimulationSystemGroup reading snapshot results from fixed step.
- Collision events: same pattern with StatefulCollisionEventBufferSystem / DynamicBuffer<StatefulCollisionEvent>.
Related Skills
[[wave5-fixed-step-simulation-system-group]], [[wave5-physics-velocity-force-application]], [[icleanupcomponentdata-runtime]], [[enableable-component]]
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.