Search Unity

Resolved How to get rect of a clicked button?

Discussion in 'Immediate Mode GUI (IMGUI)' started by eses, May 2, 2021.

  1. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    Hi.

    I can't seem to be able to figure this out today.

    I need to get the position of a click inside a button. If I do something like this:
    Code (CSharp):
    1. if (GUILayout.Button("", GUILayout.Width(tileSize), GUILayout.Height(tileSize)))
    2. {
    3.     Debug.Log(GUILayoutUtility.GetLastRect());
    4. }
    I get:
    (x:0.00, y:0.00, width:1.00, height:1.00)


    So clearly the previous rect data isn't there yet.

    I guess it could be something to do with IMGUI state, like layout and repaint, but I can't seem to be able to figure this out... feels like I've maybe forgotten something...

    I know I can get the last rect elsewhere outside of a button click, like this:
    Code (CSharp):
    1. // Skip layout
    2. if (Event.current.type == EventType.Layout)
    3.       continue;
    4.  
    5. // OK rect data
    6. lastRect = GUILayoutUtility.GetLastRect();
    Any help would be much appreciated.
     
  2. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    I will answer my self.

    I figured I'll skip using button.

    What I do instead:

    Loop all rectangular areas I want to draw. For each rectangle, reserve an area, as I'm using automatic layout of EditorGUILayout in Editor Window:
    Code (CSharp):
    1. var area = GUILayoutUtility.GetRect(tileSize, tileSize);
    Then store this rect data and other stuff in some custom struct, which I put in a List.

    Later in code, when editor is not in Layout phase (I guess I'll have to check that, not sure) I will loop the data structs and see if mouse was clicked in a rect that belongs to that object. After I know this I can figure out where in that rect I clicked:
    Code (CSharp):
    1. // later in code
    2. foreach (var data in rectData)
    3. {
    4.     // other checks here
    5.  
    6.     if (data.rect.Contains(Event.current.mousePosition))
    7.     {
    8.         // do stuff
    9.     }
    10. }