[June - 1st week tip]
When connecting events like Touched to multiple objects in a loop, use a named function instead of an unnamed one. (anonymous)
Example with unnamed functions (not recommended):
local RootFolder = workspace:WaitForChild("Parts")
for _, part in ipairs(RootFolder:GetChildren()) do
if part:IsA("BasePart") then
part.Touched:Connect(function(otherPart)
local character = otherPart.Parent
if character and character:FindFirstChild("Humanoid") then
print("Player touched the part:", otherPart.Name)
end
end)
end
end
Using an anonymous function inside a loop creates a new closure for every iteration.
Closures can capture external variables and hold references that the Garbage Collector (GC) might not release properly, which can drive to memory leaks over time.`
Better approach using named functions:
local RootFolder = workspace:WaitForChild("Parts")
local function OnPartTouched(otherPart)
local character = otherPart.Parent
if character and character:FindFirstChild("Humanoid") then
print("Player touched the part:", otherPart.Name)
end
end
for _, part in ipairs(RootFolder:GetChildren()) do
if part:IsA("BasePart") then
part.Touched:Connect(OnPartTouched)
end
end
Learn more:
Let us know if you’ve got questions or want to share your own scripting tips!
Happy building!