- Home /
selecting a button by just hovering the mouse over it... how?
I'm making a menu system that makes it possible to use mouse and controller input at the same time, it's working great until now but I wonder if it's possible to make a button get selected when the mouse pointer is only hovering over it. This is in order to avoid having two buttons that appear to be selected at the same time (According to the Eventsystem object, in reality only one is being selected, the other one is being "highlighted" by the mouse pointer).
I was thinking of something along these lines of this code:
void Start ()
{
eve = GameObject.FindGameObjectWithTag("EventSystem").GetComponent<EventSystem>();
}
void Update ()
{
if(eve.IsPointerOverGameObject() && eve.currentSelectedGameObject!= /***highlighted gameobject***/ )
{
eve.SetSelectedGameObject(/***highlighted gameobject***/);
}
}
The /highlighted gameobject/ thing is the part I don't know how to obtain, is there a way to retrieve the gameobject button that is being highlighted by the mouse pointer?
Thanks in advance.
Answer by voporak5 · Aug 05, 2015 at 05:58 AM
You want void OnMouseOver() or void OnMouseEnter() for entering or void OnMouseExit() for exiting of course
http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseOver.html
just be sure the script that has these methods is attached to the game object that you want to hover over
that's kind of the thing I wanted to avoid, since I didn't want to have to attach a script to every single button in every single menu I have (it is very prone to unwanted errors if I happen to forget one of the buttons), I was thinking something like the script I wrote above so I get a single global script that controls all the selections made by the mouse pointer. Is there a way to retrieve the highlighted button by using the PointEventData class for example? I really have no clue on how to use it. Thanks a lot!
You would have to do a raycast from your camera in the direction of your cursor by converting the screen space coordinates to real world coordinates. Google raycast to cursor for that. And when the ray collides with the object, run the function that you want