- Home /
Run script on keypress
Hi There.. I have a textfield script which works well and I would like to run it with a keypress. 'if (Input.GetKeyDown(KeyCode.F2))...' but don't how to incorporate it. How would I do this? Here is the script..
var btnColorOn : Color = Color(1.0f, 1.0f, 1.0f, 1.0f);
var btnColorOff : Color = Color(0.4f, 0.4f, 0.4f, 1.0f);
private var btnColor = btnColorOff;
private var username : String = String.Empty;
private var password : String = String.Empty;
private var correctLogin : boolean;
function Update()
{
correctLogin = (username == "user" && password == "admin");
var speed = Time.deltaTime * 4;
var targetColor = correctLogin ? btnColorOn : btnColorOff;
btnColor.r = Mathf.MoveTowards(btnColor.r, targetColor.r, speed);
btnColor.g = Mathf.MoveTowards(btnColor.g, targetColor.g, speed);
btnColor.b = Mathf.MoveTowards(btnColor.b, targetColor.b, speed);
btnColor.a = Mathf.MoveTowards(btnColor.a, targetColor.a, speed);
}
function OnGUI()
{
var windowRect : Rect;
windowRect.x = Screen.width / 2 - 100;
windowRect.y = Screen.height / 2 - 50;
windowRect.width = 200;
windowRect.height = 100;
GUI.Window(0, windowRect, OnWindowGUI, "Code");
}
function OnWindowGUI()
{
username = GUILayout.TextField(username);
//password = GUILayout.PasswordField(password, '*'[0]);
password = GUILayout.TextField(password);
GUI.color = btnColor;
if (GUILayout.Button("Enter") && correctLogin)
{
// Add your login code here...
enabled = false;
Application.LoadLevel ("next_level");
}
GUI.color = Color.white;
}
Answer by save · Oct 17, 2011 at 09:11 AM
You'd use something like this:
//Declare outside any function var loginWindow : boolean = false;
//Inside update if(Input.GetKeyDown(KeyCode.F2)) { loginWindow = !loginWindow; }
//Wrap this around your login screen if(loginWindow) { //Login window here }
Thanks for answering but I keep getting this error.. 'Unexpected token: if'. I don't seem to be putting in the correct place. Have tried lots of combinations.
Double-check your code for semicolons and parentheses?
Look at the line number that the error returns, check above that line if you've forgot to close something.
Your answer
Follow this Question
Related Questions
What key was pressed? 4 Answers
Create GUIText by pressing key 1 Answer
Can't get simple script to work? 4 Answers
how can I destroying a spawn object ? 1 Answer
turning audio on and off 1 Answer