Question by
thunderball001 · Jun 09, 2016 at 12:05 PM ·
gameobjectscript.disableenable
How to enable and disable a script on an game object by pressing a keyboard button?
#pragma strict
var onoff : boolean;
var testObject : GameObject;
function Update () {
if(Input.GetKeyDown("p")){
if (onoff == true)
testObject.active = true;
if (onoff == false)
testObject.active = false;
}
Comment
you need to update your onoff variable, but still the @Dave Carlile answer is a better way
Answer by Dave-Carlile · Jun 09, 2016 at 12:08 PM
If you just want to toggle the button then you can use some simple boolean logic.
if (Input.GetKeyDown(KeyCode.P))
{
testObject.SetActive(!testObject.activeSelf);
}
"!" is the "not operator". It takes a boolean value and returns the opposite. So if activeSelf
is true it returns false, and if it's false it returns true. This has the effect of toggling the value back and forth between true and false.