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 loop through several objects and create an event for each?

I have some models in Workspace and I want a local script to create a OnClick event for all the parts that use ClickDetectors. I made a loop function but I'm having a hard time figuring out how to relate the event to the current part.

for i,v in pairs(game.Workspace.cars:GetChildren()) do
	but=v:FindFirstChild("but")
	if but then
		but.ClickDetector.MouseClick:connect(function(player)
			local car=game.Workspace.RemoteEvents:WaitForChild("OwnCar")
			local test=car:InvokeServer(but)
		end)
	end
end

This will allow a person to click a button to own a car but it always sends the last "but" or part from the loop even if they click a different button, any way to get the current part clicked from the event?

1 answer

✓ Accepted answer

Beware your scopes

Your script is right in all senses except for its scoping. You're missing a local.

for i,v in pairs(game.Workspace.cars:GetChildren()) do
    local but=v:FindFirstChild("but")
    if but then
        but.ClickDetector.MouseClick:connect(function(player)
            local car=game.Workspace.RemoteEvents:WaitForChild("OwnCar")
            local test=car:InvokeServer(but)
        end)
    end
end

Why does this work?
When you have a local in a new scope, you create a closure. This means that the local can not be changed by anything outside of the scope or closure. It also means that the local variable is always the same local variable. The reason that your original code was broken is that it defaulted back to the global environment for every function, which you changed on every loop.

1 comment

0

I didn't know scoping actually did that, thanks!

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