- Home /
Closing an editor window causes OnGui error
I have a simple editor script that I want to run from an EditorWindow but am running into a minor problem:
I have an OnGUI function that displays a string and two buttons. When you click the first button it will run a function and then close the window. When you click the second button it will just close the window.
Everything functions normally but after the first button runs it's function and closes I get an "ArgumentException: You can only call GUI functions from inside OnGUI". However the line it brings me to is inside an OnGUI call. Is there something I'm missing? Here is the OnGUI function that runs from my class that inherits from EditorWindow.
void OnGUI()
{
GUILayout.Label("Save current scene in order to continue!", EditorStyles.boldLabel);
if(GUILayout.Button("Yes"))
{
bool shouldContinue = EditorApplication.SaveScene(EditorApplication.currentScene);
if(shouldContinue)
{
Foo();
this.Close();
}
}
if(GUILayout.Button("No")) //this is where the console error brings me if I hit the Yes button
{
this.Close();
}
}
Answer by sneftel · Jun 21, 2011 at 05:47 PM
Put a return
after each this.Close
call. After you've closed the window, you shouldn't do any further GUIing.
I've tried this and have gotten a "NullReferenceException: Object reference not set to an instance of an object
UnityEditor.DockArea.EndOffsetArea() at ..... Editor/$$anonymous$$ono/GUI/DockArea.cs 726)
UnityEditor.DockArea.OnGUI() at ....... Editor/$$anonymous$$ono/GUI/DockArea.cs654)"
Strange. Are you sure there isn't extra code in that function you're not showing?
Foo() is a function that opens up all my scenes one by one and runs a script that assigns persistent Unique ID's to objects then saves the level before switching to the next scene. It doesn't run any OnGUI related code.
It's possible that some of the loading/saving stuff going on is causing UnityGUI to get confused. Here's a possible workaround: Ins$$anonymous$$d of running Foo() directly from OnGUI, ins$$anonymous$$d have a boolean in the class, initially set to false, which is set to true ins$$anonymous$$d of calling Foo() from OnGUI. Then, have the OnDestroy function check if that boolean is true, and if it is, then it runs Foo(). That way it doesn't happen during GUI drawing.
It runs into the same problems even if I run Foo() from OnDestroy(). I'm willing to let it slide for now as the error doesn't actually break anything and is only run from in Editor, Foo() still performs perfectly with the expected results. The error is just an eyesore that I would like to get rid of. Thanks for your help so far though.