Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

i am doing a project with Unity3D . in the interface there is a textbox. once user input some text and and press enter key then i want to read the text in text box. so please tell me how to programmatically detect the key press event in unity3D - C# using MonoDeveloper.

share|improve this question
up vote 2 down vote accepted

It's a little tricky. It's pretty confusing if you have a solid background with the web platform, JavaScript and DOM Events in partcular, where most of the events are abstractized in closures for each control.

In Unity, the Events are fired globally on GUI. You must then check them, and act accordingly.


  • while the GUIWindow is drawn, listen for your EventType on Event.current (the event that just happened).
  • if needed, check it against your GUI controls.
  • if all the requirements have been matched, do something.


using UnityEngine;

public class Somegui : MonoBehaviour

private string inputValue = "";
private bool windowShouldBeDrawnCondition = false;

void Update()
    // open dialog upon Enter
    if (Input.GetKeyDown(KeyCode.Return))
        windowShouldBeDrawnCondition = !windowShouldBeDrawnCondition;

void OnGUI()
    if (windowShouldBeDrawnCondition)
        // draw dialog
        GUILayout.Window(0, new Rect(100, 100, 200, 0), DrawMyWindow, "Window Title");

void DrawMyWindow(int windowID)
    // check for keydown event
    if (Event.current.type == EventType.KeyDown)
        // no matter where, but if Escape was pushed, close the dialog
        if (Event.current.keyCode == KeyCode.Escape)
            windowShouldBeDrawnCondition = false;
            return; // no point in continuing if closed

        // we look if the event occured while the focus was in our input element
        if (GUI.GetNameOfFocusedControl() == "input" && Event.current.keyCode == KeyCode.Return)

    inputValue = GUILayout.TextField(inputValue);

    // in case nothing else if focused, focus our input
    if (GUI.GetNameOfFocusedControl() == string.Empty)

private void SubmitInputValue()
    // do not proceed if empty
    if (inputValue.Length > 0)
            // do something

        inputValue = ""; // usually, upon sending, the field should be reset

Cannot test this at the moment, but it should work.

I have given, I hope, pretty understandable and reasonable comments to grasp what is fully going on there.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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