- Home /
Question by
MileSplit · Jan 03, 2013 at 09:56 PM ·
javascriptif-statementsnoobquick
(NOOB Q) Whats wrong with my script? Two if's?
edit(moved from answer)
Wow thats embarrassing :( I posted the wrong code :(
#pragma strict
function Start () {
}
var torch: boolean = false;
var torchGo: GameObject;
function Update ()
{
{
if (Input.GetKeyUp("t")&&(torch == false))
light.range = 25;
torch = true;
}
{
if (Input.GetKeyUp("t")&&(torch == true))
light.range = 0;
torch = false;
}
}
Im trying to make it so that when you press t it turns the torch on/off. Thanks for the fast response, you guys are awesome! :)
Comment
Best Answer
Answer by ExTheSea · Jan 03, 2013 at 10:00 PM
So you should do it kinda like this:
var torch: boolean = false;
var torchGo: GameObject;
function Update ()
{
if (Input.GetKeyUp("t")&&(torch == false)){
light.range = 25;
torch = true;
}
else if (Input.GetKeyUp("t")&&(torch == true)){
light.range = 0;
torch = false;
}
}
or:
var torch: boolean = false;
var torchGo: GameObject;
function Update ()
{
if (Input.GetKeyUp("t"){
if(torch == false)){
light.range = 25;
torch = true;
}
else{
light.range = 0;
torch = false;
}
}
}
Answer by Piflik · Jan 03, 2013 at 10:57 PM
You need to make the second if into an else if, or they will always be executed both.
Also your brackets are wrong...this is how an if statement should look like:
if(something) {
//do something
}
Answer by Eric5h5 · Jan 03, 2013 at 11:24 PM
Should use the KeyCode enum rather than strings. Also it would be better to disable the light rather than setting the range to 0.
function Update () {
if (Input.GetKeyUp (KeyCode.T)) {
light.enabled = !light.enabled;
}
}