I am wondering whether this door script could cause memory leaks due to the creation of many new connections every time the function is fired. Here is the script:
hinge.ClickDetector.MouseClick:Connect(function()
for _,v in pairs(doorModel:GetChildren()) do
if v.Name ~= "Hinge" and v:IsA("BasePart") then
local offset = hinge.CFrame:Inverse() * v.CFrame
game:GetService("RunService").Heartbeat:Connect(function(dt)
v.CFrame = hinge.CFrame * offset
end)
end
end
tween:Play()
end)
The script intends to allow for the door model’s parts to be tweened, following the door concept in this article: CFrames | Roblox Creator Documentation
I also would like to know if putting the for loop outside of this function would be more performance friendly.
First I would suggest would first be to have just one .Heartbeat event, and move the loop inside of it:
local connection = game:GetService("RunService").Heartbeat:Connect(function(dt)
for _,v in pairs(doorModel:GetChildren()) do
-- ...
end
end)
-- ... can call connection:Disconnect when the tween completes
This makes things easier on you, because you only have one connection object to keep track of and disconnect. It also makes things nicer for the task scheduler.
Second, some unsolicited advice:
Don’t Connect() every time you click. You always want the door to be the same shape, so why bother ensuring that only while the door is moving? Just move the Heartbeat event outside everything else. It’s very cheap to CFrame anchored parts.
…Maybe, you don’t need the Heartbeat at all! Have you thought about welding the parts together, once, at the start of the script, and then just letting ROBLOX handle all this? You’re basically re-implementing welds here!