Objects created in Editor script lose their reference after Play/Stop?

My C# editor class (the target script) declares a public GameObject, which is instantiated in the initial Reset() function via:

folder = new GameObject("My Folder");

But after going in to Play mode and stopping again, folder now has a null reference. It (and its contents) are still in the Hierarchy, but I can’t access them without a reference.
I’m quite new to C#, coming from C++, so I’m still a bit fuzzy on allocation and persistence.

Is the problem because the script is [ExecuteInEditMode] ?

What do I need to do to keep a reference to ‘folder’?

Thanks

AFAIK editor scripts aren't executed in edit mode. If you need an update then just attach a delegate to the EditorApplication.update callback. There are others as well and a list of them is [here][1]. [1]: http://docs.unity3d.com/Documentation/ScriptReference/EditorApplication.html

–

1 Answer

1

This is expected behavior for editor scripts. You should do this:

const string FOLDER_NAME = "My Folder";

private GameObject folder;

void Awake()
{
    folder = GameObject.Find(FOLDER_NAME) ?? new GameObject(FOLDER_NAME);
}

Thanks, that's certainly going to be useful for ensuring certain objects exist or are recreated. In this case though, maybe it won't work because by simply re-making the folder I'll lose all the contents ( a bunch of prefabs). So, does this mean the expected method should be to simply rebuild EVERYTHING each time?

–