AGENT SKILL

icleanupcomponentdata-runtime

React to entity destruction at runtime by attaching a cleanup component that survives DestroyEntity, allowing a system to detect destroyed entities, release associated resources, and finalise true ...

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

01 前言 Front Matter

name
icleanupcomponentdata-runtime
tags
[ "structural-change", "lifecycle" ]
metadata
{ "tier": 3, "internal-only": true }
description
React to entity destruction at runtime by attaching a cleanup component that survives DestroyEntity, allowing a system to detect destroyed entities, release associated resources, and finalise true ...

03 SKILL.md 正文

ICleanupComponentData — Runtime Entity Lifecycle

Intent

React to entity destruction at runtime by attaching a cleanup component that survives DestroyEntity, allowing a system to detect destroyed entities, release associated resources, and finalise true removal.

Use When

An entity owns external resources (GPU buffers, physics bodies, audio instances, spatial index entries, registry slots) that must be explicitly released when the entity is destroyed. Any system that needs an "on-destroy" callback pattern.

Avoid When

The entity has no associated resources requiring cleanup — cleanup components add chunk overhead for entities that don't need them. Do not use in the baking world without [BakingType] (see [[baking-type-cleanup-component]] for baking lifecycle tracking).

Senior Pattern

  • Declare public struct MyCleanup : ICleanupComponentData { /* resource handles */ }.
  • A setup system adds MyCleanup to entities when they are created (or when the resource is acquired).
  • DestroyEntity removes all non-cleanup components but keeps MyCleanup — the entity persists in a "tombstone" state.
  • Cleanup system query: .WithAll<MyCleanup>().WithNone<MyMainComponent>() — matches only destroyed entities.
  • Cleanup system: releases resource, then ecb.RemoveComponent<MyCleanup>(entity) — triggers true entity destruction.

Code Template

public struct AudioInstanceCleanup : ICleanupComponentData
{
    public int AudioHandle;
}

// Setup system — adds cleanup when audio entity is created
[BurstCompile]
public partial struct AudioSetupSystem : ISystem
{
    public void OnUpdate(ref SystemState state)
    {
        var ecb = SystemAPI
            .GetSingleton<BeginSimulationEntityCommandBufferSystem.Singleton>()
            .CreateCommandBuffer(state.WorldUnmanaged);

        foreach (var (audio, entity) in
            SystemAPI.Query<RefRO<AudioSource>>()
                .WithNone<AudioInstanceCleanup>()
                .WithEntityAccess())
        {
            int handle = AcquireAudioHandle(audio.ValueRO.ClipId);
            ecb.AddComponent(entity, new AudioInstanceCleanup { AudioHandle = handle });
        }
    }
}

// Cleanup system — detects destroyed audio entities, releases resources
[BurstCompile]
public partial struct AudioCleanupSystem : ISystem
{
    public void OnUpdate(ref SystemState state)
    {
        var ecb = SystemAPI
            .GetSingleton<BeginSimulationEntityCommandBufferSystem.Singleton>()
            .CreateCommandBuffer(state.WorldUnmanaged);

        // WithNone<AudioSource> = entity was destroyed (cleanup survived)
        foreach (var (cleanup, entity) in
            SystemAPI.Query<RefRO<AudioInstanceCleanup>>()
                .WithNone<AudioSource>()
                .WithEntityAccess())
        {
            ReleaseAudioHandle(cleanup.ValueRO.AudioHandle);
            ecb.RemoveComponent<AudioInstanceCleanup>(entity);  // triggers true destruction
        }
    }
}

Anti-Patterns

  • Query .WithAll<MyCleanup, MyMainComponent>() — matches live entities, not destroyed ones. Correct pattern is WithNone<MainComponent>.
  • Forgetting to RemoveComponent<MyCleanup> after processing — entity persists forever as a tombstone, chunk space permanently consumed.
  • Adding cleanup without a corresponding system to remove it — permanent entity leak.
  • Using ICleanupComponentData for state that should be handled by ECB DestroyEntity alone — unnecessary complexity.

Runtime Risks

  • Missing cleanup removal: entity never truly destroys, archetype chunk fills with tombstones over time, memory leak.
  • Wrong query (WithAll instead of WithNone on main component): processes live entities as if they're destroyed, incorrect resource release.

Performance Notes

Tombstone entities occupy chunk space from DestroyEntity until cleanup removal. In high-entity-count games with frequent destruction, delayed cleanup accumulates. Always process and remove cleanup in the same frame it's detected.

Architecture Guidance

ICleanupComponentData is the ECS equivalent of a destructor. Use it deliberately — only for entities with genuine resource associations. Keep the cleanup component lean (just the handles needed for release). The setup + tombstone + cleanup pattern is a three-system lifecycle: acquire → use → release.

Related Skills

[[entity-command-buffer]], [[ecb-system-timing]], [[baking-type-cleanup-component]]

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