- Home /
Check if mouse is over a button
Since the search feature doesn't seem to be working, i'll ask in hope that this hasn't already been answered. Is there a way to check if a GUI button is being hovered over? I need to know that so I can have a tool-tip appear next to the mouse for when it is hovering (inventory stuff).
Answer by clunk47 · Jun 28, 2013 at 05:50 AM
Yes. Use a rect for the button defined in Start or Awake function. Then use a Vector2 for the mouse position. Finally, check if the rect contains the current mouse position. Try something like this. Here is a C# example.
using UnityEngine;
using System.Collections;
public class EXAMPLE : MonoBehaviour
{
Rect rect;
Vector2 mouse;
void Start()
{
rect = new Rect(0, 0, 256, 128);
}
void Update()
{
mouse = new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y);
if(rect.Contains(mouse))
{
DoSomething();
}
}
void OnGUI()
{
if(GUI.Button(rect, "Button1"))
{
DoSomething();
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613105027im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Setting Scroll View Width GUILayout 1 Answer
Can someone help me fix my Javascript for Flickering Light? 6 Answers
How can I display text and change color of objects when I roll over them with the mouse? 1 Answer
Limit on GUI Components? 0 Answers
How To Make Ammo & Realod for Gun & Spark for Gun ? 0 Answers