I’m trying to turn on and off the light form my frashlight object, using the same Mouse button (Mouse3)…
But it doesn’t work…
The code agrees to let me turn ON the light using the button, but when I click that same button again,
the light should turn off… But it doesn’t. It just stays on…
If lightOn is true, the if statement runs and sets lightOn to false, so the next if statement runs too. This is where “else if” becomes of paramount importance. (Also you need to use Down or Up rather than just GetKey.) Or you can just toggle it like this, though you have to ensure that light.intensity is 0 or 5 to start with or else it won’t work right:
function Update () {
if (Input.GetMouseButtonDown(2)) {
light.intensity = 5 - light.intensity;
}
}