Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Custom Editor: GUI.Button not responding but displaying hover effect

Discussion in 'Immediate Mode GUI (IMGUI)' started by ThatAccountBlaBlaBla, Oct 6, 2023.

  1. ThatAccountBlaBlaBla

    ThatAccountBlaBlaBla

    Joined:
    Oct 25, 2017
    Posts:
    4
    I am trying to create a custom Editor for a class inheriting ScriptableObject. In this window I want to show a grid and give the option to click the cells. Because I need specific positions for it because it's a hex grid, I need to use GUI.Button instead of GUILayout.Button.

    The GUI.Button grid has the highlight effect but does not respond to the clicks on it. I even tried getting the event directly through type and position... but no luck.

    This is the GUI code:
    Code (CSharp):
    1. public override void OnInspectorGUI() {
    2.             serializedObject.Update();
    3.             for (int x = 0; x < width; ++x) {
    4.                 for (int y = 0; y < height; ++y) {
    5.                     Rect rect = new Rect(GetCellPosition(x, y), textureSize);
    6.                     GUI.color = white;
    7.                     if (selectedCell.x == x && selectedCell.y == y)
    8.                         GUI.color = yellow;
    9.  
    10.                     bool buttonClicked = Event.current.rawType == EventType.MouseDown && rect.Contains(Event.current.mousePosition);
    11.                     if (GUI.Button(rect, hexagon) || buttonClicked) {
    12.                         selectedCell = new Vector2Int(x, y);
    13.                     }
    14.                 }
    15.             }
    16.  
    17.             serializedObject.ApplyModifiedProperties();
    18.         }
    And this is a capture of what it creates. You can see the highlight of the first element of the second row.

    upload_2023-10-6_1-31-14.png
     
  2. zeonni

    zeonni

    Joined:
    Apr 8, 2020
    Posts:
    2
    Looks like `bool buttonClicked ` not needed
    Try this:
    Code (CSharp):
    1. if (GUI.Button(rect, hexagon)) {
    2.     selectedCell = new Vector2Int(x, y);
    3. }
    And I recommend assign GUI.changed when you change any state of view. It force to repaint window. So finally:
    Code (CSharp):
    1. if (GUI.Button(rect, hexagon)) {
    2.     selectedCell = new Vector2Int(x, y);
    3.     GUI.changed = true;
    4. }
     
    Last edited: Oct 12, 2023
  3. ThatAccountBlaBlaBla

    ThatAccountBlaBlaBla

    Joined:
    Oct 25, 2017
    Posts:
    4
    Yes, as I mentioned in the description it's something I added as extra and did not work anyway. It doesnt not affect in the default behaviour of the GUI.Button call bc it's an OR.

    Repainting does nothing to the Button interaction as far as I know because what I explained is that it never gets to the if interaction inside GUI.Button anyway.