What is the purpose of this line?
I am making an editor script. In the documention of PopUpWindow I saw an example like this:
Rect buttonRect;
void OnGUI()
{
GUILayout.Label("Editor window with Popup example", EditorStyles.boldLabel);
if (GUILayout.Button("Popup Options", GUILayout.Width(200)))
{
PopupWindow.Show(buttonRect, new PopupExample());
}
// This line is the one I don't understand
if (Event.current.type == EventType.Repaint) buttonRect = GUILayoutUtility.GetLastRect();
}
}
So the line:
if (Event.current.type == EventType.Repaint) buttonRect = GUILayoutUtility.GetLastRect();
Why is it being used? What is it doing?
Answer by Dave-Carlile · Jul 10, 2017 at 08:28 PM
OnGUI
can be called multiple times per frame for things like layout, actual rendering, etc. That line is checking to see if OnGUI
is being called to repaint and only setting buttonRect
on that event. Refer to the EventType documentation for the meanings of the events.
Thank you very much. I think I phrased the question poorly, I was really just confused about what buttonRect would be before a repaint event. But it's clear now that a repaint event will be involved with button presses no matter what. Else we'd see errors with this.
I believe it's trying to find out where the button was drawn so it can do a popup at that position. It's using the GUILayout methods so the code doesn't know in advance where the button is going to be. Once the code gets the Repaint event the Layout event has already happened so they can find where the button is and assign it to buttonRect.