Turn a light on or off

I wanted the player to be able to turn a flashlight (spotlight) on and off. Here is a script my friend made:

var on : boolean = true;
var light : GameObject;

function Update()
{
        if(Input.GetMouseButtonDown(0) && on == true)
        {
                on = false;
        }
        if(Input.GetMouseButtonDown(0) && on == false)
        {
                on = true;
        }
        if(on == true)
        {
                var light.active = true;
        }
        if(on == false)
        {
                var light.active = false;
        }
}

When I tried it, a compiler error said “Unexpected token: …”. What did I do wrong?

You have a few problems with this code. Partly the issue is your unfortunate issue of naming your global game object variable ‘light’. Plus you want to enable disable the light component, not the game object. Here is an alternate:

#pragma strict

var go : GameObject;
 
function Update(){
	if(Input.GetMouseButtonDown(0)) {
		go.light.enabled = !go.light.enabled;
	}
}

Note if you attach the script directly to the game object that has the light component, you can simplify it even more:

#pragma strict
 
function Update(){
	if(Input.GetMouseButtonDown(0)) {
		light.enabled = !light.enabled;
	}
}

Why don’t you delete the syntax: ‘var’ in any statement that is not in a variable declaration statement?