GUI - Button hover change text color (Solved)

This has been driving me nuts. There is a bug in the GUI that prevents .hover and .onHover not working with text on a button. This is how it is worked around.

Additionally you’ll see a simple click and swap texture button another user posted as a solution.
Note: This code is dynamically creating 10 buttons. That’s the reason the Rects are being created on the fly.

There is a delay on the hover swap that seems to be based on the OnGUI execute speed. If anyone has some thoughts on how to add another change handler,
like:
if (GUI.Button(layerVisPos, “”, new GUIStyle()))

for:
onHover, that would be a welcome find.

Hope this help some folks that never got their answer to this question.

Cheers,
Doc

void OnGUI()
    {
        for (int i = 0; i < 10; i++)
        {
            // CLICK AND SWAP TEXTURE BUTTON
                // Button Rect
                Rect layerVisPos = new Rect(4, i * 26, 26, 26);

                // Button Clicked
                if (GUI.Button(layerVisPos, "", new GUIStyle()))
                    if (layerVisState)
                        layerVisState = false;
                    else
                        layerVisState = true;
               
                // Display proper texture
                if (layerVisState)
                    GUI.DrawTexture(layerVisPos, layerVisOn);
                else
                    GUI.DrawTexture(layerVisPos, layerVisOff);

            // HOVER CHANGE TEXT COLOR BUTTON
                // Rect
                layerSelectPos = new Rect(56, (i * 26), position.width - 54, 25);

                //  Detect hover and swap color
                curEvent = Event.current;
                if (layerSelectPos.Contains(curEvent.mousePosition))
                    guiButtonStyle.normal.textColor = Color.white;
                else
                    guiButtonStyle.normal.textColor = Color.black;

                // Hover Text Button
                GUI.Button(layerSelectPos, "Layer Name", guiButtonStyle);
        }
    }

Wha BLAMMM!!

This will give you a rollover that updates instantly and is only triggered when you are over the window itself.

  void Update()
    {
        try
        {
            if (mouseOverWindow.GetType() == (typeof(YourWindowEditorClassHere)))
                Repaint();
        }
        catch { }
    }

Note: Admittedly I believe try/catch statement to be bad coding, but it exists for just such a situation.
mouseOverWindow.GetType() can not be compared to null when you are on another monitor(I have a few). It will throw an exception no matter what you test it against.

Happy Coding,
Doc

1 Like

Are you fcking kidding ?

2 Likes