In my Tutorial screens I draw line from a piece of text in a GUILayout.Label to an object on screen.So I want to find the bounding GUI rect for a GUILayout control. Does anyone have a way to get the bounding rectangle from GUILayout control?
The best solution I have come up with is to write my own custom GUILayout controls that return the bounding layout rectangle. like the following .(The code below is copied from one of Nicholas’s posts)
// do some initialization for GetRect.
var content = GUIContent ("Button Text");
var style = GUIStyle ("button");
// Gets a rect with the size needed for "Button Text" when rendered with the "button" style.
var r = GUILayoutUtility.GetRect (content, style);
GUI.Button (r, content, style);
return r
// do some initialization for GetRect.
var content = GUIContent ("Button Text");
var style = GUI.skin.GetStyle( "Button" );
// Gets a rect with the size needed for "Button Text" when rendered with the "button" style.
var r = GUILayoutUtility.GetRect (content, style);
GUI.Button (r, content);
return r
if you use GUILayoutUtility.GetLastRect() you should put the related code in a if block checking for Event.current.type==EventType.repaint , because OnGUI is called many times and during repaint events it will have the correct rect other time the layout may not be ready yet so it returns the wrong rect.