- Home /
run editor script when just returning from play mode
I'm creating a prefab during runtime that I want to automatically load into my scene when I exit play mode / first return back to editor mode.
Is there a hook for this ?
Answer by Baste · Oct 04, 2014 at 11:06 PM
The way you do this is to include a script that's set to ExecuteInEditMode in your scene. When you enter and exit play mode, the script's OnDestroy will be called in the mode it is exiting, and it's Awake will be called in the mode it is entering.
Then, you simply check Application.isPlaying in both methods, and save a persistent message (say in PlayerPrefs) saying that the thing should be spawned.
I wrote up a little example script, it's been tested and should work:
[ExecuteInEditMode]
public class DoStuffWhenExitPlayMode : MonoBehaviour
{
void Awake()
{
if (!Application.isPlaying)
{
Debug.Log("Awake in edit mode");
if (PlayerPrefs.GetInt("should spawn") == 1)
{
PlayerPrefs.SetInt("should spawn", 0);
//Do spawning here, this object shows up in the scene.
GameObject exampleObject = new GameObject();
}
}
}
void OnDestroy()
{
if (Application.isPlaying)
{
Debug.Log("Destroyed in play mode");
PlayerPrefs.SetInt("should spawn", 1);
}
}
}
Thanks, I didn't realize that the script would get Awake() and OnDestroy() called for both modes.
Your answer
Follow this Question
Related Questions
Initialising List array for use in a custom Editor 1 Answer
Can I auto run a script when editor launches or a project finishes loading? 4 Answers
Launch Unity in safe mode? 2 Answers
Fastest way to instantiate and move multiple game objects in the editor 3 Answers
Better way to call function from another script from editor script? 1 Answer