- Home /
How to turn on a light, then off with the same button.
Hi, I'm trying to turn the headlights on, and off with the same button I started scripting a mounth ago and just can't change this basic thing. So my script is way out off bounds and i'd appreciate help ^^ :
private var lightson = false;
function Update () {
if(Input.GetButton("headlights")){
lightson = true;
light.intensity = 1;
}
if(Input.GetButton("headlights")){
lightson = false;
light.intensity = 0;
}
}
This question is similar to *http://answers.unity3d.com/questions/5270/a-simple-light-switch*, but has a few unique points which aren't covered in that answer which need explaining, so I think it warrants its own answer.
Answer by duck · Oct 14, 2010 at 07:28 PM
Simple question with a fairly simple answer, but here's a few subtle points:
You don't need to track a separate boolean on/off value. Lights have their own "enabled" boolean property which can be used to switch them on and off.
You can "toggle" a boolean by using the "not" operator, like this: myBool = !myBool;
You need to use GetButtonDown rather than GetButton, otherwise the light will continue to toggle every frame while the key is held down. GetButtonDown only occurs once, when the key is pressed, then doesn't trigger again until the key is released and pressed again.
So, combining those points into something like this should do the job:
function Update() {
if(Input.GetButtonDown("headlights")) {
light.enabled = !light.enabled;
}
}
Thanks,i almost cried myself to hapiness. You're awesome and i got a lot to learn. One more thing : where do you get those kinda tricks ? The Referance ?
Those sort of things mainly come from both reading the reference manual, and experience :-)
Thank you @duck this really helped me out as well.
Your answer
Follow this Question
Related Questions
Toggle Scripts On & Off 1 Answer
Light.intensity and Lumen comparison 0 Answers
Changing light Intensity though script does nothing 1 Answer
light intensity change with easing problem!! 1 Answer
How to make flary light reflection 1 Answer