cross-entity-lookup
Read component data from entities not in the current iteration — either via a snapshot copy (ToComponentDataArray) for simple read-only cases, or via ComponentLookup for random access by entity ID.
- License 许可
- MIT
- 最近更新
- 2026-07-25
- Stars
- ★ 8
- Forks
- 0
01 前言 Front Matter
- name
- cross-entity-lookup
- tags
- [ "core", "query" ]
- metadata
- { "tier": 3, "internal-only": true }
- description
- Read component data from entities not in the current iteration — either via a snapshot copy (ToComponentDataArray) for simple read-only cases, or via ComponentLookup for random access by entity ID.
03 SKILL.md 正文
Cross-Entity Lookup
Intent
Read component data from entities not in the current iteration — either via a snapshot copy (ToComponentDataArray) for simple read-only cases, or via ComponentLookup for random access by entity ID.
Use When
Spatial queries, targeting, nearest-neighbour, graph traversal, or any system where entity A needs to read data from entity B that is not co-iterated.
Avoid When
The relationship is static and can be expressed as a component reference (Entity field) — use ComponentLookup with a pre-stored entity handle. Avoid ToComponentDataArray for entity counts above ~10k per frame due to copy cost.
Senior Pattern
- Snapshot approach:
var data = query.ToComponentDataArray<T>(Allocator.Temp)— simple, read-only, disposed at end of OnUpdate. - Job-accessible snapshot:
query.ToArchetypeChunkArray(state.WorldUpdateAllocator)— passes chunk array to job without per-element copy. - Random access in job:
ComponentLookup<T> lookup = SystemAPI.GetComponentLookup<T>(true)— pass to job, access vialookup[entity]. - Always mark ComponentLookup
[ReadOnly]in the job if not writing — prevents false write dependencies. - Use
state.WorldUpdateAllocator(notAllocator.Temp) for data passed to jobs.
Code Template
// Snapshot read (simple, main-thread):
var enemyPositions = m_EnemyQuery
.ToComponentDataArray<LocalTransform>(Allocator.Temp);
// ... use enemyPositions ...
enemyPositions.Dispose();
// ComponentLookup in a job:
[BurstCompile]
partial struct TargetingJob : IJobEntity
{
[ReadOnly] public ComponentLookup<Health> HealthLookup;
void Execute(ref TargetSelector selector, in PotentialTargets targets)
{
for (int i = 0; i < targets.Count; i++)
{
var h = HealthLookup[targets[i]];
if (h.Current > 0) { selector.Best = targets[i]; break; }
}
}
}
// In OnUpdate:
state.Dependency = new TargetingJob
{
HealthLookup = SystemAPI.GetComponentLookup<Health>(true)
}.ScheduleParallel(state.Dependency);
Anti-Patterns
- Using Allocator.Temp for data passed to a job — Allocator.Temp is scoped to the main thread frame; jobs may outlive it.
- Not marking ComponentLookup [ReadOnly] when only reading — serialises parallel jobs unnecessarily.
- Calling EntityManager.GetComponentData<T>(entity) inside a per-entity loop — one managed call per entity, defeats ECS performance model.
- ToComponentDataArray on a very large query every frame — O(n) copy cost.
Runtime Risks
- Allocator.Temp data in a job: dangling pointer, memory corruption, or safety exception.
- Non-readonly ComponentLookup in parallel job: safety system reports write conflict.
Performance Notes
- Allocator.Temp: cheapest for data created, used, and discarded within one main-thread frame.
- WorldUpdateAllocator: lives one frame, job-accessible, cheaper than Persistent.
- ComponentLookup has cache-miss penalty vs sequential iteration — acceptable for sparse lookups, costly for dense O(n²) patterns.
Architecture Guidance
Cross-entity reads are a common performance hotspot. For dense many-to-many relationships, consider spatial partitioning (NativeMultiHashMap by cell) rather than O(n²) ComponentLookup.
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.