How to destroy linked components when object is destroyed?

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 had this same issue and I was able to solve it by passing the destroy code in an anonymous function to EditorApplication.delayCall.

[ExecuteInEditMode]
public class MyComponent : MonoBehaviour
{

  [Serializable]
  List<UnityEngine.Object> dependants = new List<UnityEngine.Object>();

  void OnDestroy ()
  {
#if UNITY_EDITOR
    foreach(var d in dependants)
    {
      var o = d; // save in a different buffer to save state for anon func
      EditorApplication.delayCall += ()=>
      {
        if(o) GameObject.DestroyImmediate(o);
      };
    }
#else
    foreach(var d in dependants)
    {
      if(d) GameObject.Destroy(d);
    }
#endif
  }