天天看點

UnityEditor報錯GUILayout: MismatchedUnityEditor報錯GUILayout: Mismatched

UnityEditor報錯GUILayout: Mismatched

自己編寫Unity的EditorWindow時,有時候會出現類似這樣的錯誤:ArgumentException: GUILayout: Mismatched LayoutGroup.ignore,多次出現這個錯誤後,發現是在與控件産生互動,同時有邏輯插入的情況造成的,而互動代碼(如

GUILayout.Button()

或者

Event事件

等)通常處于

BeginHorizontal() -- EndHorizontal()

或者

BeginVertical() -- EndVertical()

以及

BeginArea() -- EndArea()

等等布局系統之間,例如,我的代碼部分就是這樣:

GUILayout.BeginArea(rect);
        ……
        var e = Event.current;
        if (e.type == EventType.MouseDown && e.button == 0 && arrowRect.Contains(e.mousePosition))
        {
	        //互動内容
        }
		……
        GUILayout.EndArea();
           

當發生點選事件後,在互動内容中又産生了新的布局,後續就會發生問題(應該是沒有執行外層end布局),導緻報錯。

解決辦法:

unity提供了一個方法中斷本次GUI繪制,在互動内容最後加入一行代碼即可:

GUIUtility.ExitGUI();

變成:

GUILayout.BeginArea(rect);
        ……
        var e = Event.current;
        if (e.type == EventType.MouseDown && e.button == 0 && arrowRect.Contains(e.mousePosition))
        {
	        //互動内容
	        GUIUtility.ExitGUI();
        }
		……
        GUILayout.EndArea();
           

參考連結:https://answers.unity.com/questions/1456761/i-get-these-2-errors-and-a-warning-message-while-i.html