0

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

1

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

2
  • This works the first time, but if I close and re-open the UI, I have to re-close and reopen it again, so it is focused again. With this code, if I want the UI to be focused, it only works every 2nd time. Do you know what the problem could be?
    – Greg
    Feb 14 at 15:55
  • Which of those? One issue might be that the UI still stays selected after you disable the object .. you could forcedly reset it via EventSystem.current.SetSelectedGameObject(null); or yourInputField.DeactivateInputField respectively before enabling it
    – derHugo
    Feb 14 at 16:14
0

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();
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.