How to turn a flashlight on/off with LMB? (JS)

Hey,

so I started making this script in JS where you can turn it on and off with RMB.
This is what I got so far.

#pragma strict

var torchState : boolean;

function Start()
{
	torchState = true;
}

function Update()
{
	if (Input.GetButtonDown("Fire1") && torchState)
	{
		GetComponent(Light).enabled = false;
		torchState = false;
	}
	if (Input.GetButtonDown("Fire1") && !torchState)
	{
		GetComponent(Light).enabled = true;
		torchState = true;
	}
}

It doesn’t work at all. Any ideas what is wrong with it?

The logic in your code goes like this: you check for button down, and turn the torch off if it’s on. Then you check for button down, and turn it on if it’s off, which it always is, because you just turned it off. You’d need to use if/else, or better yet, don’t bother with any of that stuff, and just toggle the light instead.

function Update () {
	if (Input.GetButtonDown("Fire1")) {
		GetComponent(Light).enabled = !GetComponent(Light).enabled;
	}
}