Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Join us on Thursday, June 8, for a Q&A with Unity's Content Pipeline group here on the forum, and on the Unity Discord, and discuss topics around Content Build, Import Workflows, Asset Database, and Addressables!
    Dismiss Notice

Question How to change a Button background color on hovering?

Discussion in 'Immediate Mode GUI (IMGUI)' started by acandael, Mar 29, 2023.

  1. acandael

    acandael

    Joined:
    Apr 7, 2021
    Posts:
    67
    Hello,

    I have a custom inspector window, with a button at the bottom. I'd like it to have a given color when hovering it.
    Here's what I did:

    Code (CSharp):
    1. [CustomEditor(typeof(FurnitureAlternatives))]
    2. public class FurnitureAlternativesEditor : Editor
    3. {
    4. ...
    5. Texture2D bwGreen;
    6. ...
    7.  
    8. private void OnEnable()
    9. {
    10.     bwGreen = MakeTex(2, 2, new Color(0.11372f, 0.73333f, 0.6941176f));
    11. }
    12.  
    13. private Texture2D MakeTex(int width, int height, Color col)
    14. {
    15.     Color[] pix = new Color[width * height];
    16.     for (int i = 0; i < pix.Length; ++i)
    17.     {
    18.         pix[i] = col;
    19.     }
    20.     Texture2D result = new Texture2D(width, height);
    21.     result.SetPixels(pix);
    22.     result.Apply();
    23.     return result;
    24. }
    25.  
    26. private GUIStyle GetButtonStyle()
    27. {
    28.     GUIStyle buttonStyle = new GUIStyle();
    29.     buttonStyle = GUI.skin.button;
    30.     buttonStyle.hover.background = bwGreen;
    31. }
    32. }
    33.  
    34. public override void OnInspectorGUI()
    35. {
    36.     ...
    37.     buttonStyle = GetButtonStyle();
    38.     if (GUILayout.Button("Save furniture position and orientation", buttonStyle))
    39.     {
    40.                // Do stuff
    41.     }
    42.     ...
    43. }
    44.  
    And here's what I observe. The normal button:
    upload_2023-3-29_10-5-32.png

    and the hovered button (hard to see it here, but there's a slight difference ;)):
    upload_2023-3-29_10-12-49.png

    So, it seems this is just the default hover behavior, not taking into account the background I defined.
    I did do some test by modifying the buttonStyle.hover.textColor, and it works well.

    Can anyone help?
    Thanks a lot,
    Arnaud
     

    Attached Files: