Check if enter is pressed inside a GUI textfield

Hi everyone,

I’m trying to find a way to check if the user presses ‘enter’ or ‘return’ after entering their player name (rather than clicking the ‘next’ button). I found this code but it wont work when the textfield is in focus.

if (Event.current.Equals (Event.KeyboardEvent (“return”)))
enter = true;

There has to be a way to check for key or input events when the user is focused on a textfield. Please help!

If it’s not already, try putting your if (Event.current.Equals (Event.KeyboardEvent ("return"))) enter = true; line before your GUI call to create the text field. I had to do something similar when a button was “eating” a mouse press.

Hi. I am a beginner in Unity, but I want to increase my knowledge, and I tried to find solution to this problem.
Look at code below(it’s C# and I added name space System(for work of Char))

void OnGUI()
        s = GUI.TextArea(new Rect(30, 30, 100, 30),s,25);
        if((s != null)&&(s.Length != 0))
        if (Char.IsControl(s[s.Length - 1]))
        //make this your action    

Here’s what I’ve come up with, there’s got to be a better way, and this is really messy to me.

(inside the OnGUI put this so that itll read it when a textfield is active)

Input.eatKeyPressOnTextFieldFocus = false;

Then inside the Window function put this - it actually does nothing in the OnGUI)

if (Event.current.Equals (Event.KeyboardEvent (“return”)))
enter = true;

This example might also help:

just get a ref : Unity - Scripting API: GUI.GetNameOfFocusedControl

This is how i’m doing this :

// Check return event before Unity Text because it use the KeyDown Event
if (GUI.GetNameOfFocusedControl() == "MyControlName") {
    if (Event.current.type == EventType.KeyDown && (Event.current.keyCode == KeyCode.KeypadEnter || Event.current.keyCode == KeyCode.Return))
        // Do something
m_value = GUILayout.TextField(m_value);
if (GUILayout.Button("Next")) {
    // Do something