EditorUtility.SaveFilePanel and BeginHorizontal cause "Object reference not set..."

I have some code like the following, that is giving me an error at the second BeginHorizontal. Does anyone know why? Does the call to SaveFilePanel cause problems for EditorGUILayout? The error only occurs if I click on the ‘Save as JSON’ button.

m_scrollPos2 = EditorGUILayout.BeginScrollView(m_scrollPos2);
EditorGUILayout.BeginHorizontal();   
if (GUILayout.Button(new GUIContent("Save as JSON", "save JSON to file"))) {
    EditorUtility.SaveFilePanel("Save data",Application.persistentDataPath, "data", "json");
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal(); // error here
...
EditorGUILayout.EndHorizontal();
...
EditorGUILayout.EndScrollView();

The traceback is like:

NullReferenceException: Object reference not set to an instance of an object

UnityEngine.GUILayoutUtility.BeginLayoutGroup (UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options, System.Type layoutType) (at /home/builduser/buildslave/unity/build/Runtime/IMGUI/Managed/GUILayoutUtility.cs:296)

UnityEditor.EditorGUILayout.BeginHorizontal (UnityEngine.GUIContent content, UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options) (at /home/builduser/buildslave/unity/build/Editor/Mono/EditorGUI.cs:7234)

UnityEditor.EditorGUILayout.BeginHorizontal (UnityEngine.GUILayoutOption[] options) (at /home/builduser/buildslave/unity/build/Editor/Mono/EditorGUI.cs:7214)

(I should add that there are many questions here about “Object reference not set” errors that are about user object references that are null. In this case, the failure – see the backtrace above – is in Unity’s code).

Yes, the SavePanel (as well as some other rare methods) will break the current layout stack because they start a new layout stack. You have to call EditorGUIUtility.ExitGUI(); after you called SavePanel. ExitGUI will raise a special exception (ExitGUIException ) that will immediately terminate the current GUI execution. This exception is silently caught by Unity.

EditorGUIUtility.ExitGUI() is not documented. However it has been suggested several times by the Unity staff in the forum. Also it’s used in the editor code of any built-in Editor \ EditorWindow that would otherwise suffer from this problem.

Other cases are:

  • opening an EditorWindow from inside OnGUI
  • using a ColorField, CurveField, ObjectField will throw an ExitGUIException because they open an EditorWindow when you click the control