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:
- 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 that:
- Gets the entities that have been provisionally destroyed and require cleanup. These are entities that contain the cleanup component, but not the tag component.
- Performs the appropriate cleanup work for the entities.
- Removes the cleanup components from the entities.