Create a cleanup component
To create a cleanup component, create a struct that inherits from ICleanupComponentData
. Make sure to add it to entities at runtime, because cleanup components cannot be baked.
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:
- Create a new tag component and add the tag component to the archetype.
- Create a new cleanup component that contains information required to clean up a certain entity archetype.
- Create a system that:
- Gets newly created entities of the target archetype. These are entities that contain the tag component but not the cleanup component.
- Adds the cleanup component to these entities.
- Create a system to handle the cleanup component removal:
- In OnUpdate, handle entities which need cleanup at runtime:
- Get the entities that have been provisionally destroyed and require cleanup. These are entities that contain the cleanup component, but not the tag component.
- Perform the appropriate cleanup work for the entities.
- Remove the relevant cleanup component(s) from the entities.
- In OnDestroy, handle entities which need cleanup at shutdown:
- Get all entities with the cleanup component, including those that still have the tag component.
- Perform the appropriate cleanup work for the entities.
- Remove the relevant cleanup component(s) from the entities.
- In OnUpdate, handle entities which need cleanup at runtime: