I have car head lights turn on/off error.
Why i don’t know 
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;
}
}
}
1 Answer
1
-
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;
}
thank you for help =D
– peginethmm i have a problem : lights don't turn off
– peginetoops, forgot to add changing the state of the boolean, answer has been updated. I have also added an edit to the answer so that mistakes like that can be avoided.
– AlucardJaythanks you =D worked
– peginetIf my answer helped, don't forget to accept it by clicking the tick under the thumbs, thanks. http://video.unity3d.com/video/7720450/tutorials-using-unity-answers
– AlucardJay