- Home /
How to focus on UI element?
I am trying to manually set the focus onto a UI element through a script. I have looked some places and the only solution I found doesn't seem to work.
I know how to use the event system, but I am working with the OUYA and the event system isn't setup to support OUYA input.
To sum, how do you manually set focus on a button and how do you manually Submit on the focused button.
JavaScript would be much appreciated.
Answer by Bunny83 · Dec 06, 2014 at 07:17 AM
Well all you need you will find in the EventSystem class. Specifically SetSelectedGameObject.
This question has already been asked here.
Answer by micha · Dec 04, 2019 at 07:39 AM
In some cases it is important to disable focus before setting focus again.
Example: I had a canvas with several buttons, a single button was selected by myButton.Select()
. Then I tried to hide my canvas (so I was disabling the canvas gameObject that included the button GameObject) and right after that I activated the canvas again - but the focus was not set on the button that had focus before.
The solution was to remember what button has been clicked/focused before. The script on the canvas was then handling OnDisable()
and OnEnable()
to disable focus and set focus again. That's it.
private void OnDisable()
{
EventSystem.current.SetSelectedGameObject(null);
}
private void OnEnable()
{
lastClickedButton.Select();
}