Log in by pressing enter while password text is in focus

Log in by pressing enter while password text is in focus

I have a very simple script which is supposed to Check if the return key is pressed while the password text is in focus. 
The issue is that I've tried all 3 methods Input.GetKeyUp, Input.GetKeyDown and Input.GetKey and they all work when the user presses the Return key 2 times at least. I need to be able to log in on one press of the return key. Here is the code I'm using:
InputField _input;
bool focused;
public System.Action Callback = () => { };
void Awake()
{
    _input = GetComponent();
}

void Update()
{
    focused = _input.isFocused;
    if (focused)
    {
        Debug.Log("Passowrd field is in focus");
        if (Input.GetKey(KeyCode.Return))
        {
            Debug.Log("ENTER KEY PRESSED via getkey");
            Callback();
        }
    }
}

Solutions/Answers:

Answer 1:

InputField.ActivateInputField() is what you are looking for. Here is an example snippet that I wrote for one of my projects:

using System;
using UnityEngine;
using UnityEngine.UI;

public class SomeClass : MonoBehaviour
{
    public event Action<string> Entry;

    [SerializeField] private InputField _inputField;

    void Awake()
    {
        _inputField.onEndEdit.AddListener (InputField_OnEditEnd);
    }

    private void InputField_OnEditEnd (string input)
    {
        if (Input.GetKeyDown (KeyCode.Return))
        {
            OnEntry (input);
            _inputField.ActivateInputField();
        }
    }

    private void OnEntry (string entry)
    {
        if (Entry != null)
        {
            Entry.Invoke (entry);
        }
    }
}

To understand why this works you need to understand how EventSystem handles selection.

Once you press Return on an InputField while editing, EventSystem ends the edit mode but leaves the InputField selected. When you press Return for the first time after end of the edit mode, the key press is consumed for entering the edit mode again. Then you would need a second Return to submit the content.

InputField.ActivateInputField() activates the edit mode for you. So when the user presses Return, it submits the content instead of being consumed for entering the edit mode.

References