Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can I toggle lighting?

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

✓ Accepted answer

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.

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.

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)

This discussion is preserved as it was. New answers, comments, and votes are closed.