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 () {


          lightson = true;
          light.intensity = 1;



          lightson = false;
          light.intensity = 0;


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;

I have the same exact problem but in VR I have a prefab when pressed has a On Button UP Unity Event but the light will either turn on butt not off or on and of really fast. I need help!! Also it has a OnButtonUp Unity event if that helps