Turning on and off light with the same button!

Hello forum.

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…

The code is:

private var lightOn : boolean = false;

function Update () {

	if(Input.GetKey(KeyCode.Mouse2)  lightOn) {
		lightOn = false;
		light.intensity = 0;
		
	}
	if(Input.GetKey(KeyCode.Mouse2)  !lightOn ) {
		lightOn = true;
		light.intensity = 5;
        }
}

Any clues on how to fix this?

You are probably looking for Input.GetMouseButtonUp.

A quick Google Search gets this:

function Update() {

if (Input.GetKeyDown(KeyCode.Mouse2)) {

if (light.enabled == true) {

light.enabled = false;

}
else{

light.enabled = true;
}
}
}

Thanks guys. :slight_smile:
I’m gonna play around with those.

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;
	}
}

–Eric

Thanks Eric, and it works now guys.

Thanks so much for your help. :slight_smile: