I have it where a light turns on and off using getkeydown and two diffrent keys but I need it to do that with only one key and I know you need to use bool to do it but I’m not sure how to use bool, I’ve looked around and still can’t figure it out. So if anyone can help that would be awesome.
private bool lightBool=true;
if (Input.GetKeyDown("space")){
if(lightBool)
{
//turn off the light
lighBool=!lightBool;
}
else
{
//turn on the light
lighBool=!lightBool;
}
}
If your still struggling this code should work:
if (Input.GetKeyDown(KeyCode.E)){
//toggle the light
GetComponent <Light> ().enabled = ! GetComponent <Light> ().enabled;
}
This works because you are setting GetComponent ().enabled to the opposite of what it currently is.
A bool (short for Boolean) is a true or false variable. And GetComponent ().enabled is a Boolean so when called it will return it’s current state. The ‘!’ Operator just means not, so if the light was enable you are calling set the light to not true.
Sorry it’s a bit wordy and the code might not be formatted well but I’m on my phone
Edit: oh and now thinking about it this probably isn’t a good way of going about it as it will toggle straight back if the key is held down for more than one update so an event driven method would be better (but I’m new to unity so I’m not sure how it would be implemented)