0

I'm going to get text input using TextField and the following is my code:

public Text textInput;

void Update()
{
    if (Input.GetKeyDown(KeyCode.Return)) {
        if (textInput.text == "go") {
            /* do something */
            textInput.text = "";
        }
    }
}

I assigned the Text element under TextField to public Text textInput, and I expected that once a player types "go" and presses enter, the TextField will be cleared and the player be able to type next sentence.

However, after I type "go" and press enter, the text in TextField remained and the focus was out.

How can I clear the TextField maintaining the focus on it?

1 Answer 1

2

I think the "problem" is that the input field by default also handles the Return key as the submission command which automatically loses the focus.

The default InputField.lineType is

SingleLine

Only allows 1 line to be entered. Has horizontal scrolling and no word wrap. Pressing enter will submit the InputField.

You could instead set it to MultiLineNewLine

Is a multiline InputField with vertical scrolling and overflow. Pressing the return key will insert a new line character.

So it doesn't automatically call the OnSubmit and lose focus when pressing the Return key.


Using that as an alternative to use Update and GetKeyDown you could use InputField.onValidateInput and do something like

public InputField textInput;

private void Awake ()
{
    textInput.lineType = InputField.LineType.MultiLineNewLine;
    textInput.onValidateInput = OnValidate;
}

private char OnValidate(string text, int charIndex, char addedChar)
{
    if(addedChar == '\n')
    {
        if(text.Equals("go"))
        {
            // Do something
        }

        textInput.text = "";
        return '';
    }

    return addedChar;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thx a lot! Probably textInput had to be an InputField object.
@dbld oh yes of course :'D didn't even note that it was not before ^^

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.