using UnityEngine;
using System.Collections;
public class GUIButtonSystem
{
public static bool TextureButton (Rect rect, Texture buttonTexture)
{
bool inButton = rect.Contains (getMousePosition ());
GUI.DrawTexture (rect, buttonTexture);
if (Input.GetMouseButtonDown (0) inButton) {
Input.ResetInputAxes ();
return true;
} else
return false;
}
public static bool TextureButtonHover (Rect rect, Texture buttonTexture, Texture buttonHoverTexture)
{
bool inButton = rect.Contains (getMousePositionVerticalSwitch ());
GUI.DrawTexture (rect, inButton ? buttonHoverTexture : buttonTexture);
if (Input.GetMouseButtonDown (0) inButton) {
Input.ResetInputAxes ();
return true;
} else
return false;
}
public static bool TextureButtonHoverSeperateRects (Rect rect, Texture buttonTexture, Rect rect2, Texture buttonHoverTexture)
{
bool inButton = rect.Contains (getMousePositionVerticalSwitch ());
GUI.DrawTexture (inButton ? rect2 : rect, inButton ? buttonHoverTexture : buttonTexture);
if (Input.GetMouseButtonDown (0) inButton) {
Input.ResetInputAxes ();
return true;
} else
return false;
}
public static void TextureHover (Rect rect, Texture buttonTexture, Texture buttonHoverTexture)
{
bool inButton = rect.Contains (getMousePositionVerticalSwitch ());
GUI.DrawTexture (rect, inButton ? buttonHoverTexture : buttonTexture);
}
private static Vector2 getMousePositionVerticalSwitch ()
{
Vector2 position = Input.mousePosition;
position.y = Screen.height-position.y;
return position;
}
}
I noticed there were a lot of people trying to use Mouse Events for adding a hover to buttons… and I decided just to release this little bit of code that took no more than 5 minutes to make.
This will allow you to create regular GUI Buttons using a Texture, all without using any GUI Functions beyond GUI.DrawTexture. You can also modify this system to have it play sounds on hover etc, as it’s very simple and only deals with one GUI Function.
You can call it from the method, onGui(), like this:
if(GUIButtonSystem.TextureButtonHover(new Rect(buttonX,buttonY,buttonWidth,buttonHeight), ButtonTexture, ButtonTexture_Hover)) {
//What happens when you click the button.
}
Hope someone finds it useful! (Btw this is in C#, but I’m sure it’d be easy to convert.)