- Home /
How to set UI button as selected on mouse over
Ok, so I have a problem that my game uses mouse, keyboard and joypad input. When the UI is activated, it always selects the first option in the UI, and you can control via gamepad fine.
However, when you move the mouse over any other option, it highlights, but the first object is still selected, thus making it look like two buttons are active.
I want to deselect the currently selected gameobject and select the one the mouse is hovering over.
I tried using the following code, but it doesnt seem to work, and I cant figure out why.
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class MouseSelector : MonoBehaviour, IPointerEnterHandler {
private void Start()
{
DontDestroyOnLoad(this);
}
public void OnPointerEnter(PointerEventData eventData)
{
if (eventData.pointerCurrentRaycast.gameObject != null)
{
EventSystem.current.SetSelectedGameObject(eventData.pointerCurrentRaycast.gameObject);
}
}
}
Please can someone help?
I have this same problem. I think if an item is playing it's "highlight" animation then it should be the selected object in the event system, but for whatever reason it doesn't work like that.
Answer by IgorAherne · Jun 07, 2017 at 03:39 AM
i think your rect transforms are overlapping.
I was going to mention using additional piece of code, such as IPointerExitHandler, but SetSelectedGameObject should override whatever is selected. Hence, capturing the "pointer leaving previous button" is not necessary.
check if your rect transforms of buttons are overlapping, or something is in front of it
Hey, thanks for replying :)
I tried that, doesnt seem to be the case, especially as the buttons are highlighting, which means the mouse must be triggering them....
Well, I cant find an elegant solution to this, so ended up using this code from another thread, and attaching it to each button... it works
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
[RequireComponent(typeof(Selectable))]
public class HighlightFix : $$anonymous$$onoBehaviour, IPointerEnterHandler, IDeselectHandler
{
public void OnPointerEnter(PointerEventData eventData)
{
if (!EventSystem.current.alreadySelecting)
EventSystem.current.SetSelectedGameObject(this.gameObject);
}
public void OnDeselect(BaseEventData eventData)
{
this.GetComponent<Selectable>().OnPointerExit(null);
}
}
Thank you! I was having the same problem and this fix worked for me.