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.
1 Answer
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.
Theory
- while the
GUIWindow
is drawn, listen for your EventType onEvent.current
(the event that just happened). - if needed, check it against your GUI controls.
- if all the requirements have been matched, do something.
Implementation
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)
{
SubmitInputValue();
}
}
GUI.SetNextControlName("input");
inputValue = GUILayout.TextField(inputValue);
// in case nothing else if focused, focus our input
if (GUI.GetNameOfFocusedControl() == string.Empty)
{
GUI.FocusControl("input");
}
}
private void SubmitInputValue()
{
// do not proceed if empty
if (inputValue.Length > 0)
{
// do something
Debug.Log(inputValue);
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.