docs.unity3d.com
Search Results for

    Show / Hide Table of Contents

    Create a cleanup component

    To create a cleanup component, create a struct that inherits from ICleanupComponentData.

    The following code sample shows an empty cleanup component:

    public struct ExampleCleanupComponent : ICleanupComponentData
    {
    
    }
    
    Note

    Empty cleanup components are often sufficient, but you can add properties to store information required to cleanup the target archetypes.

    Perform cleanup

    You can use cleanup components to help you manage entities that require cleanup when destroyed. Unity prevents you from destroying an entity that contains a cleanup component.

    When you try to destroy an entity with an attached cleanup component, Unity removes all non-cleanup components instead. The entity still exists until you remove all cleanup components from it.

    To perform cleanup for entities of a specific archetype:

    1. Create a new tag component and add the tag component to the archetype.
    2. Create a new cleanup component that contains information required to clean up a certain entity archetype.
    3. Create a system that:
      1. Gets newly created entities of the target archetype. These are entities that contain the tag component but not the cleanup component.
      2. Adds the cleanup component to these entities.
    4. Create a system to handle the cleanup component removal:
      1. In OnUpdate, handle entities which need cleanup at runtime:
        1. Get the entities that have been provisionally destroyed and require cleanup. These are entities that contain the cleanup component, but not the tag component.
        2. Perform the appropriate cleanup work for the entities.
        3. Remove the relevant cleanup component(s) from the entities.
      2. In OnDestroy, handle entities which need cleanup at shutdown:
        1. Get all entities with the cleanup component, including those that still have the tag component.
        2. Perform the appropriate cleanup work for the entities.
        3. Remove the relevant cleanup component(s) from the entities.

    Additional resources

    • Tag components
    In This Article
    Back to top
    Copyright © 2024 Unity Technologies — Trademarks and terms of use
    • Legal
    • Privacy Policy
    • Cookie Policy
    • Do Not Sell or Share My Personal Information
    • Your Privacy Choices (Cookie Settings)