Hi.
I am having a lot of trouble with detecting whether the user has pressed the Enter key while a TextField has focus. When Enter is pressed the text in the TextField should be sent (I am making a chat).
However, I am not able to detect the key press in the first place. Obviously, Input.GetKeyDown does not work, since the TextField has focus. I have instead tried the following, which works perfectly fine in the Unity editor, but not when building the application:
private bool enterPressed = false;
void OnGUI()
{
Event e = Event.current;
if (e.type == EventType.KeyDown && e.keyCode == KeyCode.Return)
{
enterPressed = true;
}
else
{
enterPressed = false;
}
}
I know that in previous versions of Unity you could use:
Input.eatKeyPressOnTextFieldFocus = false;
Apparently this has been changed.
Any suggestions?
Use a temporaly string to save text from GUI.TextField.
You can use Regex(Class) to check regular expression.
And can use String.Constains or String.IndexOfAny to detect new line key pressed.
using UnityEngine;
using System.Collections;
using System.Text.RegularExpressions;
public class NewBehaviourScript : MonoBehaviour {
int maxCharacters = 30;
string textField="";
bool textFieldEnabled = true;
Rect position = new Rect(20,20,200,30);
//Regex Url = new Regex("[^a-z0-9]");
Regex regularExpression = new Regex("^[a-zA-Z0-9_]*$");
char[] newLine = "
\r".ToCharArray();
/*Regular expression, contains only upper and lowercase letters, numbers, and underscores.
* ^ : start of string
[ : beginning of character group
a-z : any lowercase letter
A-Z : any uppercase letter
0-9 : any digit
_ : underscore
] : end of character group
* : zero or more of the given characters
$ : end of string
*/
void OnGUI(){
if(textFieldEnabled){
string str = GUI.TextField(position,textField,maxCharacters,GUI.skin.textField);
//This methods no detect new line using string variable
//string str = GUI.TextField(position,textField,maxCharacters);
//string str = GUI.TextField(position,textField);
if(regularExpression.IsMatch(str)){
if(str.IndexOfAny(newLine)!=-1) Action(textField); //New Line detected
else textField = str; //All OK, copy
} else Debug.Log("Irregular expression detected");
}
}
void Action(string str){
textFieldEnabled = false;
Debug.Log("New Line Detected");
}
}