- Home /
Unity UI Mouse + Keyboard navigate, Un-Highlight button choice on mouse over
Hi,
I have Mouse + Keyboard navigation in menu. I use sprite swapping transition to show different button sprite when the button is highlighted. (For example Unselected = black, Selected = White) Now the problem I have run into is that if one button is active for keyboard controls, and considered selected and thus has selected sprite as button background, and I hover mouse over different button. Both buttons are considered "Active" and both have selected sprite as button background.
Is there any fix to this problem?
Thanks in advance
Answer by daterre · May 23, 2017 at 08:37 AM
I found a workaround for navigation buttons. Attach the script below to each navigable button. More details on this forum post.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
[RequireComponent(typeof(Selectable))]
public class HighlightFix : MonoBehaviour, 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);
}
}
It's a good idea and it works, I am just a bit surprised that after several years that this problem exists, it's still necessary to use this kind of "dirty" workaround in order to be able to use mouse and keyboard or controller at the same time. Well done though mate!
I didn't expect this to fix my issue, but lo and behold, I popped this component onto my button from 'Dialogue System for Unity' and boom, it works normally now. =)