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

This does not work. It always counts the last range. Not the current one. Any help?

local gen = {
    gen1 = game.Workspace.GeneratorOne.Screen.ClickDetector,
    gen2 = game.Workspace.GeneratorTwo.Screen.ClickDetector,
    gen3 = game.Workspace.GeneratorThree.Screen.ClickDetector,
    gen4 = game.Workspace.GeneratorFour.Screen.ClickDetector
};
local lights = game.Workspace["Light Switch"].Lights:GetChildren()

for _, button in pairs(gen) do
    button.MouseClick:Connect(function()
        for _, light in pairs(lights) do
            if light.SpotLight.Range == 0 then
                print("bob")
				light.Material = Enum.Material.Plastic
            else
                print(tostring(light.SpotLight.Range))
				light.Material = Enum.Material.Neon
            end
        end
    end)
end

1 comment

0

It only checks when you click it

1 answer

This is because you are only putting the same event in every click detector. Instead, make a separate script and copy it to the click detector. Events in loops is s big no no.

Also that’s the point of a click detector. It runs code on mouse click.

--server script, MAKE SURE ITS DISABLED!!

script.Parent.MouseClick:Connect(function(plr)
    -- code
end)
for _, button in pairs(gen) do
    local clickCode = script.ClickDetectorScript:Clone()
    clickCode.Parent = button
    clickCode.Disabled = false -- you were supposed to set it to true manually in properties
end

3 comments

0

"Events in loops is s big no no." - there's nothing inherently wrong with binding a function to an event inside a loop??

0

Events in a loop is bad practice. Instead put the loop inside an event.

0

But what if you're binding one function to different events in different places, which is what seems to be going on here.

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