# EditorApplication.SaveScene followed by EditorWindow.Close throws InvalidOperationException

I'm making a really basic custom editorwindow that has a textbox for a scene name, creates a scene with that name and closes itself. Trimmed down to the essence it looks like this:

public void OnGUI()
{
if (!GUILayout.Button("Create")) return;

if (CreateScene())
{
Close();
}
}

private bool CreateScene()
{
var path = string.Format("{0}/{1}.unity", Application.dataPath, "bug");
EditorApplication.NewScene();
return EditorApplication.SaveScene(path);
}


This throws an InvalidOperationException

InvalidOperationException: Operation is not valid due to the current state of the object
System.Collections.Stack.Peek () (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections/Stack.cs:321)
UnityEngine.GUILayoutUtility.EndLayoutGroup () (at C:/BuildAgent/work/d63dfc6385190b60/artifacts/EditorGenerated/GUILayoutUtility.cs:223)
UnityEngine.GUILayout.EndVertical () (at C:/BuildAgent/work/d63dfc6385190b60/artifacts/EditorGenerated/GUILayout.cs:266)
UnityEditor.HostView.OnGUI () (at C:/BuildAgent/work/d63dfc6385190b60/Editor/Mono/GUI/DockArea.cs:135)


When I remove either the save or the close, the exception doesn't rise.
My guess is the project window needs to finish refreshing somehow.

UPDATE

Tried a frame of delay
Tried AssetDatabase.Refresh()
Tried GUILayout.EndVertical()
Filed a bug
Bugtrack: http://fogbugz.unity3d.com/default.asp?668833_nmit48pnb2fivo27

Looks like the GUI is finishing building after the Close() by automatically calling EndVertical().

Try adding an GUILayout.EndVertical(); before the Close();.

Or if that doesn't work delaying your Close call by one frame, something like:

private bool close = false;

public void OnGUI()
{
if(close){
Close();
return;
}

MapName = EditorGUILayout.TextField("Map Name", MapName);

var requestedSave = GUILayout.Button("Create") || PressedEnter();
if (!requestedSave) return;

if (!CreateScene())
{
Debug.Log("Failed saving");
}
close = true;
}

• Am I alone in thinking that's fishy? I haven't started a StartVertical anywhere. I am thinking it is because the project view is repainting to account for the new scene in the listing. Jan 27 '15 at 8:10
• Will try the delay when I have my home computer in front of me Jan 27 '15 at 8:11
• Yeah its fishy. If you can make a small project to reproduce the bug you should submit a bug report. If the delay fixed the crash mention it to them as well, put the work-around in the code commented-out with a good description. Jan 27 '15 at 12:25
• Reported the bug through their Report A Bug window. Didnt get any tracking id or such Feb 1 '15 at 16:19