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

How do I change all the lighting in my game without tons of code?

I have a script for a button, so that once pressed it sounds an alarm and changes the lighting around the map. The script runs perfectly, but the repeated code to change all the separate lights seems a little ridiculous, so I am hoping there is a way to avoid it? I have around 50 lights total (so this script is merely a snippet), all of which located in the exact same place, "game.Workspace.FacilityLighting".

function onClicked()

local Alarm = script.Parent.BreachAlarm 

if Alarm.Playing == true then
	
	Alarm.Playing = false
	game.Workspace.FacilityLighting.Light1.SurfaceLight.Color = Color3.new(255/255, 0/255, 0/255)
	game.Workspace.FacilityLighting.Light2.SurfaceLight.Color = Color3.new(255/255, 0/255, 0/255)
	game.Workspace.FacilityLighting.Light3.SurfaceLight.Color = Color3.new(255/255, 0/255, 0/255)
	game.Workspace.FacilityLighting.Light4.SurfaceLight.Color = Color3.new(255/255, 0/255, 0/255)
	
else
	 Alarm.Playing = true
end
end

script.Parent.ClickDetector.MouseClick:Connect(onClicked)

1 answer

✓ Accepted answer

If the only thing you have in your game.Workspace.FacilityLighting folder are these lights, then you can simply loop through the folder and set all the colors. If there are other things, you can loop through the folder but you need to check to make sure it is a light. It's definitely safer and smarter to go the latter route.

local alarm = script.Parent:WaitForChild("BreachAlarm")
local facilityLighting = workspace:WaitForChild("FacilityLighting")
local colorToChangeTo = Color3.new(1, 0, 0)
-- if you prefer RGB values from 0 to 255:
colorToChangeTo = Color3.FromRGB(255, 0, 0)

local function onClicked()
	if alarm.Playing then -- you don't need == true
		alarm.Playing = false
		
		-- loop through all the lights
		for _, light in pairs(facilityLighting:GetChildren()) do
			-- check to make sure there are SurfaceLights inside the part
			local surfaceLight = light:FindFirstChild("SurfaceLight")
			if surfaceLight then
				surfaceLight.Color = colorToChangeTo
			end
		end
	end
end

Hope this helps! :)

3 comments

0

think u mean for _, light in pairs(facilityLighting:GetChildren()) on line 12?

0

Expected identifier, got ')', appears on the closing bracket beside the final end.

0

Code fixed. Sorry :p

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