Inconsistent destruction of converted entities/components during subscene unload

Hi, I’m having an inconsistency issue related to the destruction of entities/components during scene unload (for instance, when exiting Play mode).
I wrote more details about my particular issue in the following thread:

Basically, I have an authoring component that implements IConvertGameObjectToEntity, it creates an entity via conversion workflow and adds a DynamicBuffer to the entity.
In the SimpleAnimationSystem that I use, it has an OnDestroy() callback.

So, when I exit Play mode, the system calls its OnDestroy callback, where it queries for
GetEntityQuery(typeof(SimpleAnimationGraphData), typeof(SimpleAnimationClipData));. Normally, it finds the entities which have those two components, then clears up their data (an animation graph/nodes), and finally disposes the entities.

But very frequently, what happens instead is that when OnDestroy is called, the entity suddenly doesn’t have its SimpleAnimationClipData component anymore, so the query fails and the data that should be cleared ends up leaking instead. There’s not any other code that destroys that SimpleAnimationClipData. So, it seems that sometimes, Unity randomly destroys that component during scene unload, I’m guessing that’s related to the conversion workflow.

Do the components that were added to the entity during the conversion workflow get auto-destroyed when the subscene (from which the conversion was made) gets unloaded? I guess that makes sense, but it’s very weird that sometimes the component is deleted before my system’s OnDestroy(), and other times the component isn’t deleted yet (the result that I want, so I can clean up my graph data).

Is there any way to ensure the component won’t get auto-destroyed before my system OnDestroy is called? And to make that scene unloading/entity cleanup behavior more consistent?

Any component that contains data required by a cleanup step should be a SystemState component. Often times that means having to copy ICD data to an ISSCD using change filters every frame.

Yes, subscenes destroy entities. And as your project grows, you’ll find ways to accidentally destroy them too.

During my tests, I was already wondering if there was some kind of “persistent component” that survived subscene unloads. SystemState component was just what I needed!

I managed to fix my issue with a SystemState component, thank you very much for the tip! :smile: