- Home /
4.6 New UI System, how to detect if a button is selected
Hi, I want to drop mouse control in a scene and instead using keyboard completely to interact with UI part in the scene. So as you know when mouse is over a button, a default button in version 4.6 would highlight to show it is focused. However, for now I only have keyboard input, could I click a button by pressing a key (like Enter) and choosing which button is focused (like using Up or Down arrow).
I have implemented the part that pressing a key to call OnClick function of a certain button by EventSystem. But I don't know how to detect if it is highlighted to show it's the target interactive UI part (like a mouse on it).
Thanks in advance.
Answer by fafase · Dec 08, 2014 at 07:08 PM
Well, using keyboard is just the same as mouse, you define the navigation either automatic or you make it yourself. Then it works.
The main issue is setting the original button. Without any code, you need to trigger one with mouse and then you can navigate (at least for what I have seen).
By code you can set which is the default one:
public class NewBehaviourScript : MonoBehaviour
{
[SerializeField] private GameObject defaultButton;
void Start()
{
EventSystem.current.SetSelectedGameObject(defaultButton, null);
}
}
It works but I can't explain why the first move requires two clicks. Maybe someone has a totally working solution.
Oh yeah that makes sense, I think it will work fine, thanks!
for some weird reason if it's not in the Start() $$anonymous$$ethod, it selects, but doesn't highlight. You can work around it like so:
defaultButton.Select();
defaultButton.OnSelect(null);