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;
}

}

1 Answer

1

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.

It work perfect!!! Thank you.