Unity 报错 Operation is not valid due to the current state

最近做 unity 项目编辑器,在按自定义按钮加载场景的时候,会出现 InvalidOperationException: Operation is not valid due to the current state 错误。

参考如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void NewScene()
{
UnityEditor.SceneManagement.EditorSceneManager.NewScene(
UnityEditor.SceneManagement.NewSceneSetup.EmptyScene,
UnityEditor.SceneManagement.NewSceneMode.Single);
}

void OnGUI()
{
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("新建场景")) NewScene();
EditorGUILayout.EndHorizontal(); //Error here

}

估计是加载场景导致 GUILayout 的堆栈错误。

找到了比较好的解决办法:

1
if (GUILayout.Button("新建场景")) NewScene();

改为

1
if (GUILayout.Button("新建场景")) EditorApplication.delayCall += NewScene;

完美 fix!

Unity 报错 Operation is not valid due to the current state

https://robinxb.com/posts/2017/unity-editor-invalid-option-fix/

作者

薯条

发布于

2017-02-14

更新于

2024-01-15

许可协议

评论