- Home /
How i turn on/off a Object with GetKeyDown?
Hi guys, I'm trying to make a script so that when I v activate the "light" and when I click again to disable, but it's not working :/
var onoff : boolean;
var luz : GameObject;
function Update(){
if(Input.GetKeyDown ("v")){
onoff = true;
}
}
function ativar () {
if (onoff == true)
luz.active = true;
if (onoff == false)
luz.active = false;
} Thanks.
Comment
Best Answer
Answer by aldonaletto · Nov 20, 2011 at 07:40 PM
You're only changing onoff to true, never to false, but that was not making any difference at all, since the function ativar were not being called. You can toggle the onoff variable true and false with onoff = !onoff each time the key is pressed, and directly assign onoff to luz.active:
var onoff : boolean; var luz : GameObject;
function Update(){
if(Input.GetKeyDown ("v")){
onoff = !onoff; // toggle the onoff variable
luz.active = onoff;
}
} NOTE: if Unity complains that "active is obsolete", use luz.enabled instead.
You don't need a variable:
function Update() {
if (Input.Get$$anonymous$$eyDown ($$anonymous$$eyCode.V)) {
luz.active = !luz.active;
}
}