From the Unity docs, it says that Dispose() is automatically called for the IComponentDatas that are on the Entity, when destroyed. This seems to be the case for managed components only
I have an unmanaged component that has a NativeArray allocated - is it possible to get the Dispose() method to be called when the entity is destroyed?
Not sure if there’s a way to do it or if it’s currently not supported
We resolved this by creating a custom cleanup system - it manually calls Dispose when the entity is about to be destroyed via a destroy tag. Would be great in the future for it to get called automatically - similar to managed components
Missed this due to the forum migration - but you can execute a query in the OnDestroy of the system to parse through all of the components and dispose of any allocations
Here’s a snippet:
public void OnDestroy(ref SystemState state)
{
EntityQuery query = state.EntityManager.CreateEntityQuery(ComponentType.ReadOnly<MyComponent>());
// Fetch all entities with MyComponent
using (var entities = query.ToEntityArray(Allocator.TempJob))
using (var components = query.ToComponentDataArray<MyComponent>(Allocator.TempJob))
{
// Dispose the NativeArray for each component
for (int i = 0; i < components.Length; i++)
{
components[i].Cleanup();
}
}
}