Car light turn on/off error

I have car head lights turn on/off error.
Why i don’t know :frowning:

var HeadLight0 : Light;
var HeadLight1 : Light;
var LightOn : boolean = false;

function Start () {

	HeadLight0.light.active = false;
	HeadLight1.light.active = false;
}
function Update () {

	if(Input.GetKey("f"))
	{
		if(LightOn == false)
		{
			HeadLight0.light.active = true;
			HeadLight1.light.active = true;
		}
	}
	else if(Input.GetKey("f"))
	{
		if(LightOn == true)
		{
			HeadLight0.light.active = false;
			HeadLight1.light.active = false;
		}
	}
}
  • GetKey : Returns true while the user holds down the key identified by name. Think auto fire.
  • GetKeyDown : Returns true during the frame the user starts pressing down the key identified by name.
  • GetKeyUp : Returns true during the frame the user releases the key identified by name.

I assume you wish to toggle the lights. Check if the key is down, then switch the light states :

var HeadLight0 : Light;
var HeadLight1 : Light;
var LightOn : boolean = false;

function Start () {
	LightOn = false;
	HeadLight0.light.active = false;
	HeadLight1.light.active = false;
}

function Update () {
	if(Input.GetKeyDown("f"))
	{
		if(LightOn == false)
		{
			LightOn = true;
			HeadLight0.light.active = true;
			HeadLight1.light.active = true;
		}
		else if(LightOn == true)
		{
			LightOn = false;
			HeadLight0.light.active = false;
			HeadLight1.light.active = false;
		}
	}
}

Edit :

Following the mantra “Don’t repeat yourself”, this can be simplified by passing the boolean value to a function :

var HeadLight0 : Light;
var HeadLight1 : Light;
var LightOn : boolean = false;

function Start() 
{
	ToggleLights( false );
}

function Update() 
{
	if(Input.GetKeyDown("f"))
	{
		if(LightOn == false)
		{
			ToggleLights( true );
		}
		else if(LightOn == true)
		{
			ToggleLights( false );
		}
	}
}

function ToggleLights( theBool : boolean )
{
	LightOn = theBool;
	HeadLight0.light.active = theBool;
	HeadLight1.light.active = theBool;
}