- Home /
Trigger 'if' statement while in TextField
I have a GUI.TextField in a unity project and the string from it is used to trigger other scripts and events. The boolean that confirms the button is pressed (passing that confirmation to other scripts) is turned to True when "Return" is pressed on the keyboard. The problem is, pressing Return only works once the user has clicked out of the TextField. I want the return key to work as trigger when the user hits it after typing (whilst still accessing the TextField). My GUI method is as follows:
void OnGUI()
{
GUILayout.Label("Find Places");
search = GUI.TextField(new Rect(10, 10, 200, 20), search, 25);
//static function TextField (position : Rect, text : String, maxLength : int) : String
if (Event.current.Equals(Event.KeyboardEvent("return")))
{
confirm = true;
}
else
{
confirm = false;
}
}
Answer by Eric5h5 · Mar 23, 2012 at 06:21 PM
void OnGUI()
{
GUILayout.Label("Find Places");
search = GUI.TextField(new Rect(10, 10, 200, 20), search, 25);
confirm = Event.current.character == '\n';
}
Interesting and unexpected solution. I'll start using this right away!
Wow would never have thought of that one! Thanks a bunch! Does '\n' represent new line?
Yep. Also I use '\t'
to detect the user hitting tab (since the built-in tab behavior is usually not what I want).
I know that the question is really old now, but this awesome! :D
Answer by GC1983 · Mar 23, 2012 at 05:08 PM
Maybe try a simple Input.GetKeyDown("return") in the Update function.
void Update()
{
if(Input.GetKeyDown("return")
{
confirm = true;
}
}
It's not a good idea to mix Update/Input with OnGUI code.
Your answer
Follow this Question
Related Questions
Adding a value after a trigger on 1 Answer
TextField moves/jumps when focused 0 Answers
input button while in a trigger? 2 Answers
How to check if a key is down in editor script 2 Answers
Lightswitch help? 3 Answers