Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How can I toggle lighting?

Asked by 8 years ago

I only know how to enable lights, but I don't now how to disable the lights with a second click.

local switch = script.Parent
local light1 = script.Parent.Parent.light1.SpotLight
local light2 = script.Parent.Parent.light2.SpotLight

light1.Enabled = false
light2.Enabled = false

local function onClick(clicked)
    light1.Enabled = true
    light2.Enabled = true
end
switch.ClickDetector.MouseClick:connect(onClick)

3 answers

Log in to vote
1
Answered by
Link150 1355 Badge of Merit Moderation Voter
8 years ago

In your onClick event callback, check whether your lights are activated or deactivated using an ifstatement and act accordingly:

if light1.Enabled then
    light1.Enabled = false
else
    light1.Enabled = false
end

If you understand boolean algebra, you can also sum that up in a single line:

light1.Enabled = not light1.Enabled

So it flips the value of light1.Enabled whatever its previous value is.

Ad
Log in to vote
1
Answered by
itsJooJoo 195
8 years ago

To make something enabled and then disabled, you simply have to call the = not line.

local switch = script.Parent
local light1 = script.Parent.Parent.light1.SpotLight
local light2 = script.Parent.Parent.light2.SpotLight

light1.Enabled = false
light2.Enabled = false

local function onClick(clicked)
    light1.Enabled = not light1.Enabled
    light2.Enabled = not light2.Enabled
end
switch.ClickDetector.MouseClick:connect(onClick)

Since you are using a bool value, when using the = not, it utilizes whether it is true or false, then does the opposite of that.

Log in to vote
1
Answered by 8 years ago

A good way to do this would be to use a boolean value, and just check and change it every time the function is run, so:

local switch = script.Parent
local light1 = script.Parent.Parent.light1.SpotLight
local light2 = script.Parent.Parent.light2.SpotLight

local IsOn = false --The boolean

light1.Enabled = false
light2.Enabled = false

local function onClick(clicked)
    if (IsOn) then --If the light is on...
        light1.Enabled = false --Turn the lights off..
        light2.Enabled = false
        IsOn = false --Tell the script that the lights are off
    else --If the light is off...
        light1.Enabled = true --Turn the lights on..
        light2.Enabled = true
        IsOn = true --Tell the script that the lights are on
    end
end

switch.ClickDetector.MouseClick:connect(onClick)

Answer this question