How to know if mouse is over a GUI.button.
I want to press 1-8 while my mouse is over a skill icon to assign shortcut to it.
How to know if mouse is over a GUI.button.
I want to press 1-8 while my mouse is over a skill icon to assign shortcut to it.
Something like this should work. I haven't tested it (so there could be typos), but this is the general idea.
You need to adjust the y-coordinate of the mouse position because the GUI uses a different screen coordinate system: Y = 0 is at the top of the screen.
function OnGUI ()
{
var theRectangle = Rect(0, 0, 200, 100);
if ( GUI.Button(theRectangle, "Press Me") ) {
print("I have been pressed");
}
var mousePosition = Input.GetMousePosition();
/* adjust the y-coordinate for the GUI's coordinate system */
mousePosition.y = Screen.height - mousePosition.y;
if ( theRectangle.Contains(mousePosition) ) {
if ( Event.current.isKey ) {
print("The following key was pressed: " + Event.current.character);
/* mark that the event has been used (thank you Ejlersen) */
Event.current.Use();
}
}
}
jahroy has answered this, even though I'm a bit confused about why one wants a `GetButtonRectangle()` method... But well, it's just a code snippet :)
Here is my suggestion:
public class Answer
{
public Rect rect = new Rect(0.0f, 0.0f, 128.0f, 32.0f);
void OnGUI()
{
if (GUI.Button(rect, "My Button is AWESOME!"))
Debug.Log("I was pressed!");
if (rect.Contains(Event.current.mousePosition))
{
// Probably want to do this in a less hardcoded way...
if (Event.current.keyCode == KeyCode.Alpha0)
{
Debug.Log("0 was pressed!");
}
// And so on...
}
}
}