DestroyImmediate(component.gameObject) destroys component but not gameObject

I got a weird problem with the DestroyImmedeate() function. First off, here’s a version of the script that I reduced to the problematic part:

using UnityEngine;
using UnityEditor;

[ExecuteInEditMode]
public class MyScript : MonoBehaviour {
    public MyComponent myComponent;
        
	void Awake() {
        myComponent = Instantiate<GameObject>(
            Resources.Load<GameObject>("Prefabs/MyComponentPrefab"),
            this.transform
        )
        .GetComponent<MyComponent>();
    }
	
	void OnDestroy () {
        if (EditorApplication.isPlaying)
        {
            Destroy(myComponent.gameObject);
        }
        else
        {
            DestroyImmediate(myComponent.gameObject); // <- this behaves wrong some times?
        }
    }
}

The problem occurs when I switch from edit to playmode. So basically, what I expect to happen, is that when the OnDestroy() function gets called, the GameObject attached to the myComponent variable gets removed completely.

Then, Awake() is called and a new instance is created, again, as a child in the hierarchy.


For some reason though, DestroyImmediate(myComponent.gameObject) is called but only the component gets removed. What stays is an GameObject containing all the other components that were attached to it despite MyComponent and it is still listed as a child of MyScript in the hierarchy.


If everything worked the whole GameObject should be gone so what am I missing here?

You’re doing some dangerous things here. ExecuteInEditMode is not ment to implement editor functionality. It’s just ment to provide live feedback while in edit mode. When you enter playmode at the time the editor scene is destroyed it got already serialized. That means when the scene gets deserialized at the beginning of playmode the object will probably be recreated from the serialized data.

This line:

DestroyImmediate(myComponent.gameObject); 

actually has no direct connection to myComponent since the expression myComponent.gameObject is a gameobject reference. So it’s impossible that it somehow is able to only destroy your component.

If you need some gameobjects / component at edit time you should set proper hideflags. However from the posted code it’s hard to determine the purpose of the script. Where is that script even attached to?