- Home /
How to call function when enter is pressed in text area?
Im trying to send information for a login system with two textfields, when i press login it sends the information perfectly but if I press enter it doesnt work. How can I detect this event with the enter key properly?
Ive got this so far:
#pragma strict
function Start () {
}
function Update () {
if(Input.GetKeyDown("enter")){
enterPressed = true;
} else {
enterPressed = false;
}
}
var enterPressed : boolean = false;
var Username : String = "";
var Password : String = "";
var loginSuc : boolean = false;
var stringText : String = "";
var loggedinUser : String = "Guest";
function OnGUI () {
GUI.Label (Rect (380, 380, 100, 750), "Username");
Username = GUI.TextField (Rect (380, 400, 200, 25), Username, 25);
GUI.Label (Rect (380, 425, 100, 750), "Password");
Password = GUI.PasswordField(Rect(380,445,200,25), Password,"*"[0],25);
if (GUI.Button (Rect (445, 480, 70, 25), "Login") || enterPressed == true)
{
checkPassword();
print ("Button pressed");
}
GUI.Label (Rect (440, 260, 120, 750), stringText);
GUI.Label (Rect (800, 60, 90, 50), "You are logged in as "+ loggedinUser);
}
function checkPassword(){
//set the WWWForm to send to the PHP page
var sendLoginInfo : WWWForm = new WWWForm();
sendLoginInfo.AddField("Username",Username);
sendLoginInfo.AddField("Password",Password);
//send the WWWForm via WWW
var getdata : WWW = new WWW("login.php",sendLoginInfo);
yield getdata; //Wait for the data to return
//if TRUE >> Load level
if (getdata.text == "true") {
login();
} else {
stringText = "Login Failed!";
}
}
function login(){
stringText = "Login Successful!";
loggedinUser = Username;
}
Answer by Kleptomaniac · Mar 11, 2012 at 03:46 AM
You use a GUI Event in OnGUI which determines whether the current event within the GUI focus is equal to the return keycode. So, in OnGUI (), you would do this:
if (Event.current.keyCode == KeyCode.Return) {
checkPassword();
}
and if you wanted to specify it as a keydown event you would go:
if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Return) {
checkPassword();
}
Hope that helps! Klep
Wow thanks that was perfect I was getting really confuse with all the different ways to detect input but none were working :D works perfect now!
Actually you should always check the event type, otherwise your code is executed for all keyboardevents that involve the return key.
Answer by unimechanic · Jul 03, 2013 at 04:12 PM
This example should help:
http://forum.unity3d.com/threads/188202-Simple-dynamic-list-editor