Is there a problem with using a for loop to connect events for multiple objects?

Hello!
I was just revisiting my old games, and I found this piece of code here:

local shopParts = workspace.shopParts:GetChildren()

for i,v in pairs(shopParts) do
	v.Touched:Connect(function(hit)
		-- Code that opens shop gui, etc.
	end)
end

iirc, I was a stupid 9 year old that wanted to learn to code in roblox, and I did, well, stuff that isn’t very… RAM friendly.
Although, it has many parts in it. Like, about 20. Imagine how many lines it would’ve took to connect one-by-one.
So, the question is, is there any problem with using a for loop to connect events for multiple objects?
Thanks in advance! (^▽^)

Nope, there is nothing wrong with the code by itself. In fact this piece of code is commonly seen used with the collection service:

Basic collection services kill brick code from the tutorial
local CollectionService = game:GetService("CollectionService")

--// First, we will loop trough all the parts with the "killers" tag using a for loop.

for _, part in pairs(CollectionService:GetTagged("killers")) do
	
	--[[
	Now that we've got our killer parts, we're gonna bind them to a function, 
    so when they get touched, they will fire that function.
	--]]
	
	part.Touched:Connect(function(hit)
		--// Classic killing brick script, nothing very interesting
		
		if (hit.Parent:FindFirstChild("Humanoid")) then
			local humanoid = hit.Parent.Humanoid
			
			humanoid.Health = humanoid.Health - humanoid.MaxHealth
		end
	end)
end

You should notice it’s the exact same as your code sample posted but using collection service to get the parts instead of :GetChildren().

The only possible problem the piece of code can cause is when there are a large amount of parts to connect like thousands or millions since events take up memory commonly seen in tycoon games. As long as that doesn’t happen it should be fine… if it does then that’s a different scripting support question to manage large amount of touched instances.

3 Likes

Thanks! I was actually thinking about implementing it into one of my games if it wasn’t bad practice.

I’ll make sure to not have a thousand parts though :sunglasses:

1 Like