- Home /
How to turn a flashlight on/off with LMB? (JS)
Hey,
so I started making this script in JS where you can turn it on and off with RMB. This is what I got so far.
#pragma strict
var torchState : boolean;
function Start()
{
torchState = true;
}
function Update()
{
if (Input.GetButtonDown("Fire1") && torchState)
{
GetComponent(Light).enabled = false;
torchState = false;
}
if (Input.GetButtonDown("Fire1") && !torchState)
{
GetComponent(Light).enabled = true;
torchState = true;
}
}
It doesn't work at all. Any ideas what is wrong with it?
Answer by Eric5h5 · Sep 17, 2013 at 08:05 PM
The logic in your code goes like this: you check for button down, and turn the torch off if it's on. Then you check for button down, and turn it on if it's off, which it always is, because you just turned it off. You'd need to use if/else, or better yet, don't bother with any of that stuff, and just toggle the light instead.
function Update () {
if (Input.GetButtonDown("Fire1")) {
GetComponent(Light).enabled = !GetComponent(Light).enabled;
}
}
Works perfectly, but how? It just says that light enabled is equal to light not being enabled?
What is happening is the enabled property of the Light is being set to the opposite value. So if enabled is false, it is set to true and vice versa.
It is shorthand for the following:
if(GetComponent(Light).enabled == true)
GetComponent(Light).enabled = false;
else
GetComponent(Light).enabled = true;
However, since you are doing it the way @Eric5h5 suggests, you save time on the process since you simply toggle the value rather than having to check the value first.
(to elaborate) you can switch a boolean to its opposite value this way.. example:
var switch : boolean = true;
switch = !switch;
//(switch now equals false)
switch = !switch;
//(equals true again)
Component.enabled is a boolean, so this works..
Your answer
Follow this Question
Related Questions
turn on and off the render of a child 1 Answer
Getting GUI texture on and off 0 Answers
Turn on/off Script 3 Answers
Turn On and Off Lights Via Script 1 Answer