I’m making a game using ECS, and I have some Entities + ComponentData that contain NativeArray(Allocator.Persistent). I know I should Dispose these NativeArray when destroying the Entity. However, the issue arises when unloading Scenes/Subscenes, as these Entities may be destroyed along with the Scene, bypassing my cleanup process. My thoughts are: 1. Can Allocator.Domain solve this problem? 2. Manually clean up all Persistent-related items before unloading the scene. Any suggestions?
Something smells wrong here, how do you have native containers on entities that are linked to a subscene?
Are you baking native containers onto components because this isn’t allowed and will not work in builds.
this entity is a Baked Prefab, so will initiate in SubScene, However, the native container is not added through Baking, they are added by a System under certain conditions.
OK, so next question is. Why not just use a dynamic buffer to make everything a lot less problematic for yourself?
To answer your actual question though, the best way imo is just to react a subscene being closed with the following code - note i believe it will take internal access
[UpdateInGroup(typeof(InitializationSystemGroup))]
[UpdateBefore(typeof(SceneSystemGroup))]
public partial struct RunBeforeSubSceneUnload : ISystem
{
/// <inheritdoc />
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
foreach (var s in SystemAPI
.Query<SceneSectionData>()
.WithAll<SceneEntityReference, SceneSectionStreamingSystem.StreamingState>()
.WithNone<RequestSceneLoaded, DisableSceneResolveAndLoad>())
{
var sceneSection = new SceneSection
{
SceneGUID = s.SceneGUID,
Section = s.SubSectionIndex,
};
foreach (var d in SystemAPI.Query<YourComponent>().WithAll<SceneSection>().WithSharedComponentFilter(sceneSection))
{
d.NativeArray.Dispose();
}
}
}
Also put in an OnDestroy that’ll iterate all components and Dispose as well when shutting down world