How do you automatically focus on an inputfield when opening/activating the UI in Unity3d?

1.2k Views Asked by At

I am making a game where you must open or activate the UI with the space bar. Now, this works perfectly fine, but it is pretty annoying that every time you open the UI you must click on the inputfield to write in it. Is there any way around this? So is there a way to open or activate the UI without having to click on the field to be able to write in it?

I looked for YouTube videos and tried to find similar problems in other forums, but wasn't able to find a script, nor was I able to find some Unity settings to do so.

2

There are 2 best solutions below

2
derHugo On

You could use e.g.

private class SelectOnEnable : MonoBehaviour
{
    private void OnEnable()
    {
        EventSystem.current.SetSelectedGameObject(null);
        EventSystem.current.SetSelectedGameObject(gameObject);
    }
}

and attach it to whatever object that should become the selected one everytime it is enabled. See EventSystem.SetSelectedGameObject

Can't test it right now but it might still require the User to hit Enter in order to also actually set the Input field into edit mode. The upper line only sets it as selected UI element (similar to using TAB in a browser).


Otherwise I think you would go through

yourInputField.DeactivateInputField()
yourInputField.ActivateInputField();

to directly set it active. See InputField.ActivateInputField. Might have to do both in combination - again can't test right now ;)

0
Greg On

Thank you very much, derHugo! Everything works like a charm now! You saved me a lot of time. Referring to your last comment, I used both of them, and it seems to work very well for me. Here is the code I used:

private void OnEnable()
{
    EventSystem.current.SetSelectedGameObject(gameObject);
    GameManager.GetComponent<InputFieldComparision>().inputFieldInMainUi.ActivateInputField();

    EventSystem.current.SetSelectedGameObject(null);
    GameManager.GetComponent<InputFieldComparision>().inputFieldInMainUi.DeactivateInputField();
}