- Home /
Turn light on/off
i have spot light n my gun and i want it turn on and off with the same button
so if i press maybe fire1 the light goes on and if i press the button again it should go off
how can i writ in javascript that the light is destroyed and respawn with the same button
like public var Lightpoint : GameObject;
if(Input.GetButtonDown("Fire1")) transform.position = Lightpoint.transform.position;
and now
if(Input.GetButtonDown("Fire1"))
destroy.Gameobject..........
how can i make it???
Answer by runevision · Apr 09, 2010 at 09:05 AM
You can toggle any bool by setting it to the opposite of its current value:
myBool = !myBool;
So you can toggle a light source by toggling its enabled state:
myLight.enabled = !myLight.enabled;
Now you want to do that if you press a certain button:
Light myLight = lightPoint.GetComponent("Light");
if (Input.GetButtonDown("Fire1")) { myLight.enabled = !myLight.enabled; }
I know this is 7 years later, but thank for explaining this concept, it has been so useful to me as I learn and practice scripting in C#. Again thank you so much for this answer :)
Answer by ACPallitta · Jun 30, 2012 at 03:48 PM
I just put this and it worked fine.
Under update put
if(Input.GetButtonDown("Flashlight")){
light.enabled = !light.enabled;
}
"Flashlight" being whatever key you want to have pressed. Quick and easy.
Answer by blue · Aug 29, 2011 at 06:59 PM
here is the java script to turn on/off a light put the script on the light source
private var on = false;
function Update(){
if(Input.GetButtonDown("fire 1")){
if(on){
light.intensity =0;
on = false;
}
else {
light.intensity =2;
on = true;
}
}
}
Answer by Leonard Kropf · Apr 09, 2010 at 11:43 AM
there is a problem it say
error UVE001 expected.Insert a semicolon at the end
there in this sentence but there is a semicolon at the end
Light myLight = lightPoint.GetComponent("Light");
If you copy/paste the code as is, it won't work. The code given is in C#, so you'd need to create a C# script (with all the attendant file/class name matching) and put the if expression inside the Update function.
Answer by markmozza · Jan 21, 2019 at 11:52 AM
Unity Tutorial with Multiple Lights https://www.youtube.com/watch?v=kqu-lsfd4qI&t=1s