I put some lights in a folder in workspace, and I’m attempting to add a toggle light switch that can flick those lights on/off. I’ve achieved half of that, but adding a debounce, or even an else statement breaks the code.
I’ve tried pretty much all I can think of, mind you I’m not an advanced coder in the slightest, so my code could look ugly. I’ll show you what you’re workin’ with.
“Living Room Lights” Is the folder containing the Parts that hold SpotLights within them.
“Delly” is just a boolean value I was gonna use for a debounce.
Don’t worry about the on/off variables, those aren’t being used right now.
on = script.Parent.Parent.On
off = script.Parent.Parent.Off
delly = script.Switch.Value
light = workspace:FindFirstChild("Living Room Lights")
script.Parent.ClickDetector.MouseClick:Connect(function()
for i,v in pairs(light:GetChildren()) do
local light = v:FindFirstChild("SpotLight")
if light then
light.Enabled = false
end
end
end)
local part = script.Parent
local model = script.Parent.Parent
local clickdetector = part.ClickDetector
local on = model.On
local off = model.Off
local delly = script.Switch.Value
local lights = workspace:FindFirstChild("Living Room Lights")
local debounce = false
clickdetector.MouseClick:Connect(function()
if debounce then
return
end
debounce = true
for i,v in pairs(lights:GetChildren()) do
local light = v:FindFirstChild("SpotLight")
if light then
light.Enabled = not light.Enabled
end
end
task.wait(5)
debounce = false
end)
You were overriding the value of the variable “light” inside the loop so I’ve changed the name of the lights folder/model to “lights” to prevent this. I’ve also added a 5 second cool down between triggers. I’ve also fixed the toggling.
You have 2 “light” variables, one at the top, and in your loop, try to avoid dupe variables.
You’d just add an else to the if statement, not the loop itself.
If you wanted to have it change the light, you can instead just set Enabled to not Enabled.
I believe I provided the exact same solution one post earlier but I don’t really mind. Remember to declare variables locally as that integrates them into the local environment which allows them to be accessed quicker from within the script.
Local variables are obtained faster than global variables because they’re integrated into the environment in which they were created. If possible, you should always use local variables over global variables, unless there’s a specific reason otherwise.
You can implement a debounce in the way I have if you still need to add one & it might be worth switching “pairs” to “ipairs” as you’re iterating over an array.
I also forgot to ask, in the code you sent, I need to change the brick color of the SpotLight’s parent Part. I can get it to change to Black, but I need it back to its Yellow color and I’m unsure where to add that line without breaking the code.