Code not working

Hello. I have this code but it’s not working for my light system. Error: Workspace.LightButton.Main.Script:9: attempt to index nil with 'Enabled'

By the way, I do have a post just from before that I got this code from.

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?

1 Like

That is because you are looking for the spotlight inside the model, not inside the parts in that model

Change Folder:GetChildren() to Folder:GetDescendants()

Still getting the same error.

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

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

Forgot to mention you have to put v:FindFirstChildOfClass in an if statement.

Try this instead:

for i, v in pairs(Folder:GetDescendants()) do
	if bool == false then
		bool = true

		if v:FindFirstChildOfClass("SpotLight") then
			v:FindFirstChildOfClass("SpotLight").Enabled = true
		end
	else
		bool = false

		if v:FindFirstChildOfClass("SpotLight") then
			v:FindFirstChildOfClass("SpotLight").Enabled = false
		end
	end
end
1 Like

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