I have a component which manages other components on the same object in the editor. I’ve implemented OnDestroy so that the primary component removes all of the ones it manages. This works fine when I want to delete the main component. However, if I delete the game object, I get the error:
Destroying object multiple times. Don’t use DestroyImmediate on the same object in OnDisable or OnDestroy.
I can’t seem to find a way around this. I’m testing for null before destroying and setting the references to null afterward, but I think Unity is trying to delete each component again after I’ve already deleted it. Is there a better way to handle the destruction of managed components?
My work around for now is to use a separate hidden child object to store the components, providing more certainty in destruction order. But I don’t like this because it alters the hierarchy. I’m trying to keep the managed components hidden and unobtrusive. I’ve tried working with ScriptableObject as an alternative, but ran into insurmountable issues with prefabs and object duplication.
I should have mentioned too: If I don't delete the managed components, then they remain after deleting the primary. There are potentially a lot of components and they're hidden, so it's important that they get deleted with their owner.
– Steven-WalkerCan you save the gameObjects to an array, pop them in a coroutine, and delete them in the next frame? Not an elegant solution, but I've never seen what you describe, so I'm not sure how to help you.
– Julien-LyngeAlso, could you consider using ScriptableObject rather than game objects if all you're doing is storing components?
– Julien-LyngeSince this is all being done in editor mode (not playing), I can't make use of yield or coroutines. And yes, I have tried the ScriptableObject route but it poses difficult problems with duplicating and prefabs.
– Steven-WalkerSorry, I somehow completely missed that this was happening in the editor. I'll have to give it some more thought.
– Julien-Lynge