- Home /
Light script flashes on and off
Hello, I have made a script to turn a light on and off when L is pressed, this goes onto my character model and it kind of works. The light starts as on, turns off when L is pressed, then if you press it again to turn it on again, it just flashes on and off.
Thanks in advance for any help, Krynn/Aaron
var torchDisabled : boolean = false;
function Update () {
var torchLight = GameObject.Find("Torch");
if (Input.GetKeyDown(KeyCode.L) && torchDisabled == false) { torchLight.light.enabled = true; torchDisabled = true; } else if (torchDisabled == true) { torchLight.light.enabled = false; torchDisabled = false; }
}
Answer by duck · Oct 22, 2010 at 03:59 PM
Hi,
The reason for the flashing is a problem with logic in your "if" and "else if" code. However, in your case your code could be reduced down to the following:
var torch : Light;
function Start() { // we find the instance once, at start var torch = GameObject.Find("Torch").light; }
function Update () { // if the key is pressed during this update, we "toggle" the enabled value if (Input.GetKeyDown(KeyCode.L)) { torch.enabled = !torch.enabled; } }
Explanation:
The "torch" var stores a reference to the actual light component on the torch, not the gameobject.
There's no need to store a separate var to remember the on/off setting as we can use the light's own "enabled" property to remember this.
When the key is pressed, we can "toggle" the enabled property by using the ! ("not") operator.
If your script is actually placed on the torch object itself, your code could be made even simpler, because no references to the torch object would be necessary.
Your answer
![](https://koobas.hobune.stream/wayback/20220613080448im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
c# light off 2 Answers
Turn On and Off Lights Via Script 1 Answer
How to make a light turn on/off 1 Answer
Turn on/off Script 3 Answers