AGENT SKILL

wave8-dynamic-buffer-invalidation

Prevent unsafe access to DynamicBuffer references after structural changes have invalidated the underlying chunk memory pointer.

License 许可
MIT
最近更新
2026-07-25
Stars
★ 8
Forks
0

01 前言 Front Matter

name
wave8-dynamic-buffer-invalidation
tags
[ "antipattern", "debug" ]
metadata
{ "tier": 3, "internal-only": true }
description
Prevent unsafe access to DynamicBuffer references after structural changes have invalidated the underlying chunk memory pointer.

03 SKILL.md 正文

DynamicBuffer Invalidation After Structural Changes

Intent

Prevent unsafe access to DynamicBuffer references after structural changes have invalidated the underlying chunk memory pointer.

Use When

  • Any system reads a DynamicBuffer reference and then performs structural changes (AddComponent, RemoveComponent, DestroyEntity, CreateEntity) on any entity in the same frame

Avoid When

  • No structural changes occur in the system — buffer references are stable within a single structural-change-free frame

Senior Pattern

// WRONG — structural change invalidates the buffer reference:
var buffer = SystemAPI.GetBuffer<WaypointElement>(entity);
EntityManager.AddComponent<DeadTag>(entity);   // structural change — buffer pointer now invalid
var count = buffer.Length;                      // undefined behavior, potential crash

// CORRECT — read buffer contents before structural change:
var buffer = SystemAPI.GetBuffer<WaypointElement>(entity);
var waypointCount = buffer.Length;             // read before structural change
var lastWaypoint = waypointCount > 0 ? buffer[waypointCount - 1] : default;

// Then defer structural change via ECB:
var ecb = new EntityCommandBuffer(Allocator.Temp);
ecb.AddComponent<DeadTag>(entity);             // deferred — buffer still valid until Playback
ecb.Playback(EntityManager);
ecb.Dispose();
// After Playback: buffer reference is invalid — do not access

// CORRECT alternative — re-fetch after structural change:
EntityManager.AddComponent<DeadTag>(entity);                      // structural change
var freshBuffer = SystemAPI.GetBuffer<WaypointElement>(entity);   // re-fetch

Anti-Patterns

  • Storing a DynamicBuffer reference in a field and reading it across system updates — invalid after any structural change.
  • Calling EntityManager.GetBuffer<T> and then EntityManager.AddComponent in the same method without re-fetching — pointer invalidation.
  • Caching buffer references in NativeArray fields between frames — never valid across structural changes.
  • Reading a buffer reference after ECB.Playback in the same method — Playback is a structural change; the reference is invalid after it.

Runtime Risks

  • Access to invalidated buffer memory causes silent data corruption or NullReferenceException.
  • The safety system catches this in editor builds (throws InvalidOperationException) but may silently corrupt in release builds — do not rely on editor-only detection.

Performance Notes

  • Re-fetching a buffer is cheap (O(1) archetype lookup). The cost of getting it wrong is a crash or corruption.
  • Always prefer ECB to defer structural changes and keep buffer references valid for the current frame's read pass.

Architecture Guidance

  • Treat DynamicBuffer references as frame-scoped and structural-change-scoped.
  • Separate read passes from structural change passes within a system's OnUpdate.
  • Use ECB to push structural changes after all reads complete.
  • If both read and structural change are required in the same method, re-fetch the buffer after the structural change.

Related Skills

[[entity-command-buffer]], [[ecb-system-timing]], [[toentityarray-snapshot-pattern]], [[structural-change-cost-model]]

04 同仓库更多 Skills

dyCuong03
dyCuong03/unity-agent-team

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.

★ 8
dyCuong03
dyCuong03/unity-agent-team

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.

★ 8
dyCuong03
dyCuong03/unity-agent-team

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.

★ 8
dyCuong03
dyCuong03/unity-agent-team

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.

★ 8
dyCuong03
dyCuong03/unity-agent-team

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.

★ 8
dyCuong03
dyCuong03/unity-agent-team

valid_skill

A complete, well-formed test fixture skill for SkillHub validation testing. Covers basic task routing and code review for Unity projects.

★ 8