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

Why does this GetChildren lightswitch not function?

Lights = game.Workspace.LightsModel:GetChildren("Light")
local lightActive = false

script.Parent.MouseButton1Click:connect(function()
	if lightActive == false then
		Lights.PointLight.Enabled or Lights.SpotLight.Enabled = true
	lightActive = true
	end
end)
script.Parent.MouseButton1Click:connect(function()
	if lightActive == true then
		Lights.PointLight.Enabled or Lights.SpotLight.Enabled = false
	lightsActive = false
	end
end)

I have a large amount of Lights in a model, I believe I did this wrong, but this is the general idea. There's SpotLights in some and PointLights in some-I believe that's my main issue. Any solutions?

1 answer

✓ Accepted answer

Combine both anonymous functions!

Lights = workspace:WaitForChild("LightsModel")
LightsTable = Lights:GetChildren()
-- ":GetChildren()" is one of those methods that DO NOT have a parameter. It just returns an array of all of the child(ren) from the given instance

isACTIVE = false

script.Parent.MouseButton1Click:connect(function ()
	if isACTIVE then
		for i, Part in pairs(LightsTable) do
			if Part:IsA("BasePart") then
				for i, Light in pairs(Part:GetChildren()) do
					if Light:IsA("Light") then
						Light.Enabled = false
					end
				end
			end
		end
		isACTIVE = false
	else
		for i, Part in pairs(LightsTable) do
			if Part:IsA("BasePart") then
				for i, Light in pairs(Part:GetChildren()) do
					if Light:IsA("Light") then
						Light.Enabled = true
					end
				end
			end
		end
		isACTIVE = true
	end
end)

Use the generic "for" loop to iterate over every value of the LightsTable array.

:IsA("") is a method that returns the class of the object.

As you can see, I went into extreme measures into checking if there's more than one light objects in a part, just in case, because I do not know what your descendants of LightModel looks like.

This script, of course, can be shortened to increase efficiency.

Lights = workspace:WaitForChild("LightsModel")
LightsTable = Lights:GetChildren()
-- ":GetChildren()" is one of those methods that DO NOT have a parameter. It just returns an array of all of the child(ren) from the given instance

isACTIVE = false

function Switch(Boolean)
	for i, Part in pairs(LightsTable) do
		if Part:IsA("BasePart") then
			for i, Light in pairs(Part:GetChildren()) do
				if Light:IsA("Light") then
					Light.Enabled = Boolean
				end
			end
		end
	end
	isACTIVE = Boolean
end

script.Parent.MouseButton1Click:connect(function ()
	if isACTIVE then
		Switch(not isACTIVE)
	else
		Switch(not isACTIVE)
	end
end)
-- "not" reverses the boolean value

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