- Home /
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.
Answer by LividPixel · Feb 21, 2015 at 05:39 AM
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.
Your answer
Follow this Question
Related Questions
Initialising List array for use in a custom Editor 1 Answer
difficulty with InitializeOnLoad and Application.isPlaying 2 Answers
Script for Application initialisation 1 Answer
Getting data from Editor into runtime 2 Answers
What is a good Javascript editor, with Syntax highlighting and checking? 5 Answers