How to get a control position on a guilayout?

How can I get the position of a control that was created using GUILayout?
Assume the code:

void OnGUI()
	{
    GUILayout.BeginHorizontal();
    if (GUILayout.Button("Button"))
      {
      //...
      }
    GUILayout.EndHorizontal();
	}

Is it possible to get the position of the displayed button within OnGUI?

Thanks

void OnGUI(){
Rect lastRect;
GUILayout.BeginHorizontal();
{
if (GUILayout.Button(“Button”)){//}
lastRect = GUILayoutUtility.GetLastRect(); //button rect
}
GUILayout.EndHorizontal();
lastRect = GUILayoutUtility.GetLastRect(); //horizontal area rect
}

GetLastRect

You need to define the position of the button on your GUI layout so you don’t need to get the position.

For example:

public GUIStyle styleExample;

public Texture2D buttonTexture;

void OnGUI()
{
if (GUI.Button (new Rect (0, 0, 100, 100), buttonTexture, styleExample))
{
//code for button press
} 
}

In that example you are creating a button which will look like the buttonTexture (.png imports work fine for this).

You are using the styleExample to help format the button automatically so it has no strange borders around it. You can further customize your fonts for GUI.Label or other GUI visual properties in the styleExample from your script in the Unity Editor.

And then you are placing the button at position (0, 0) which is the top left corner.

The button is sized (100, 100) which is 100x100 pixels.

So that is how I go about knowing where the position and size of the button will be.

There is a lot more details of how you can make it format to any screen size, resolution etc. which you can find in many other answers here.

If you are looking for other quick references I believe I tried to explain how I use the OnGUI() system in more detail in this thread: