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 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