How can I turn all these lights off at once with a button?

Hey all. So basically, I have this stage room, and I want all the lights in this room to turn off on the press of a button. There is a spot light in each of the parts.

image

local button = script.Parent.ClickDetector
local Folder = game.Workspace.EventRoomLights

button.MouseClick:Connect(function()
	for i, v in pairs(Folder:GetChildren()) do
		if v:IsA("SpotLight") then
			v.Enabled = false
		end
	end
end)

If you can help, it would be much appreciated!

local button = script.Parent.ClickDetector
local Folder = game.Workspace.EventRoomLights

button.MouseClick:Connect(function()
	for i, v in pairs(Folder:GetDescendants()) do
		if v:IsA("SpotLight") then
			v.Enabled= false
		end
	end
end)

the difference was that it used :GetDescendants()
or you could do

local button = script.Parent.ClickDetector
local Folder = game.Workspace.EventRoomLights

button.MouseClick:Connect(function()
	for i, v in pairs(Folder:GetChildren()) do
		v:FindFirstChildOfClass("SpotLight").Enabled = false
	end
end)
2 Likes

Thank you very much! I am really bad with for loops, and I will try and get better!

Hello again. I just tried applying this script to another light system, and obviously tweaked it to it would work, but it is giving me an error Workspace.LightButton.Main.Script:9: attempt to index nil with 'Enabled'

local button = script.Parent.ClickDetector
local Folder = game.Workspace.SpotLights
local bool = false

button.MouseClick:Connect(function()
	for i, v in pairs(Folder:GetChildren()) do
		if bool == false then
			bool = true
			v:FindFirstChildOfClass("SpotLight").Enabled = true
		else
			bool = false
			v:FindFirstChildOfClass("SpotLight").Enabled = false
		end
	end
end)

image

Any clue why this is?

For this you probably want to rename the part that holds the spotlight, then edit the script to reflect that, or you could just use my :GetDescendants() method.

GetDescendants() method
local button = script.Parent.ClickDetector
local Folder = game.Workspace.EventRoomLights

button.MouseClick:Connect(function()
	for i, v in pairs(Folder:GetDescendants()) do
		if v:IsA("SpotLight") then
			v.Enabled= false
		end
	end
end)

For this system, the :FindFirstChildOfClass() is returning nil because there is no spotlight as one of its children.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.