InitializeOnLoad: Gameobject being destroyed?

I’m confused I’m using [InitializeOnLoad] extending the editor and it creates a gameobject. When it creates it, it also adds a script. On the script, I have this:

void OnDestroy() {
Debug.Log("Destroyed");

}

Once I start up unity, it says “Destroyed” in the console, and the object isn’t there in the heirarchy. I don’t know at all why unity is destroying it. I’m not destroying it in code, either.

In the static constructor for whatever class you have [InitializeOnLoad] attached to, put something like this:

EditorApplication.playmodeStateChanged = () =>
    	{
    		if (EditorApplication.isPlayingOrWillChangePlaymode && !EditorApplication.isPlaying)
    		{
    			GameObject myObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
    			myObject.AddComponent<Rigidbody>();
    			myObject.transform.position = new Vector3(2, 2, 2);
    			myObject.name = "MyObject";
    		}
    	};

Note that this will create and add the object every time the game is run, so you will have multiple instances of the object.

You’ll need to add some sort of check to make sure that your object hasn’t been already added to the scene in the above code.