- Home /
EditorGUI Get Rect of GUILayout Objects
I want to resize a draggable GUI.Window (Node) automatically to fit its content. But how can I get the defining rect of the GuiLayout Objects I want to draw in the node?
//Gets called from EditorWindow
public void DrawNode() {
textContent = GUILayout.TextArea (content, GUILayout.ExpandHeight(true));
if(GUILayout.Button("Clear")){
textContent = "";
}
//rect = TextArea + Button Total size
}
The EditorWindow draws the nodes:
private void OnGUI(){
BeginWindows ();
for(int i = 0; i < nodes.Count; i++) {
nodes[i].rect = GUI.Window(i, nodes[i].rect, DrawNodeWindow, nodes[i].title);
}
EndWindows ();
}
//function that actually draws the nodes as dragWindow
private void DrawNodeWindow(int id) {
if (id < nodes.Count) {
nodes [id].DrawNode ();
GUI.DragWindow ();
}
}
Answer by Bunny83 · Aug 25, 2018 at 11:51 AM
You can use GUILayoutUtility.GetLastRect after a GUILayout control method to get the layouted rect of that control. However this will only return a valid rect when not executing the layout event. As you might know every event that is processed by OnGUI / OnInspectorGUI is paired with a layout event which is executed right before the actual event. During the layout event the rect is something like (0,0,-1,-1) afaik.
Note if you want to get the combined size of two or more elements you may want to wrap them in a seperate horizontal / vertical layout group and get the rect from that.
From your code it's not really clear where your "DrawNode" method is called from. You added the comment that it's called from "EditorWindow". Did you mean called from the GUI.Window callback?
Note that you can use GUILayout.Window instead of GUI.Window. It is able to resize itself when needed. Though it will only ever "grow" the size but never reduce it.
Note that GetLastRect does return the actual layouted rect, not the size that might be needed / wanted for the content. Layouting always depends on the space available.
Thanks for your answer. I renamed DrawWindow() to DrawNode() and forgot to change that in the editorWindow too so sorry for the confusion. Edited post.
The GUILayout.Window function solved the problem for auto resizing. As you pointed out the TextArea does not shrink itself back to normal if the text is deleted, so I guess I need to wrap them in the layout group.
I changed back to GUI.Window() to make use of the VerticalGroup but now the nodes completely disappear:
public void DrawNode(){
Rect contentRect = (Rect)EditorGUILayout.BeginVertical();
textContent = GUILayout.TextArea (textContent , GUILayout.ExpandHeight(true));
if(GUILayout.Button("Clear")){
textContent = "";
}
EditorGUILayout.EndVertical();
rect = contentRect ;
}
Debugging prints the rect is 0,0,0,0