I have some GameObjects that create entities, which they destroy in their OnDestroy handler. This works just fine, except when the game is shutting down, about 20% of the time, the EntityManager will have already been deallocated by the time OnDestroy runs. This results in shutdown errors like these:
InvalidOperationException: The Unity.Entities.EntityManager has been deallocated, it is not allowed to access it
Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle.CheckWriteAndThrowNoEarlyOut (Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle handle) (at <fad2bd984a474a969b1042b2d70ac590>:0)
Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle.CheckWriteAndThrow (Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle handle) (at /Users/builduser/buildslave/unity/build/Runtime/Export/Jobs/AtomicSafetyHandle.bindings.cs:162)
Unity.Entities.EntityManager.GetCheckedEntityDataAccess () (at Library/PackageCache/com.unity.entities@0.11.1-preview.4/Unity.Entities/EntityManager.cs:70)
Unity.Entities.EntityManager.DestroyEntityInternal (Unity.Entities.Entity* entities, System.Int32 count) (at Library/PackageCache/com.unity.entities@0.11.1-preview.4/Unity.Entities/EntityManagerCreateDestroyEntities.cs:341)
Unity.Entities.EntityManager.DestroyEntity (Unity.Collections.NativeArray`1[T] entities) (at Library/PackageCache/com.unity.entities@0.11.1-preview.4/Unity.Entities/EntityManagerCreateDestroyEntities.cs:140)
I wonder if ECS objects should not destruct before GameObjects do on shutdown?
Full disclosure: my mind has been warped by 15 years of C++, so apologies if this makes no sense in your memory-managed, sci-fi future world, where you always label your references and the Garbage Collector deallocates things when it feels like it, on its way from the farmer’s market while snacking on organic goji berries.