Unity: Getting GUILAyout: Mismatched LayoutGroup.repaint? Try EventType.Repaint

I built a great custom Unity Editor window. It does all the things.

Except it's buggy.

It's a sort of window-based GUI. I have mini windows inside of a normal Unity custom Editor Window.  At some point I implemented the ability to rearrange which window is on top.

Then the trouble started.

"GUILayout: Mismatched LayoutGroup.repaint"

I've been struggling on and off for days with this. The exception is thrown at odd places deep in my GUI code.

But it turns out the problem is when I was reordering the stack of windows.

Each window tracks if it is currently selected. This is used to change the style of the window. What I decided to do is, at the end of the OnGUI loop, check if the window that is selected is at the end of the list of windows (since they are rendered from 0 on up). If the selected window is not at the end of the list, then move it.

This generally gets the windows to stack properly, but then I sometimes get these odd exceptions.

It turns out it has something to do with how Unity's Editor GUI works. It performs multiple passes, and at certain passes it expects things to not change. Changing the order of the windows changes the order of EditorGUILayout calls, among other things.

The fix was to ensure that I change the window ordering when the current EventType is Repaint:

if(Event.current.type == EventType.Repaint) {
    if(selectedNode > -1 && selectedNode < nodes.Count - 1) {
      // Change window order here