Game laggy from many parts falling

Hello developers, I’m making a game where blocks and stuff fall from the sky and when they hit the building they unanchor them to sorta “Break” them and I have many parts to make each wall (Sorta like make one wall out of a bunch of tiny parts) but of course with that many parts unanchoring and falling the game lags horribly. So I added a cooldown before other parts can unanchor more but it still lags. So any ideas? Heres the script used to make parts unanchor.
while wait() do
function touched(hit)
if hit.Parent:FindFirstChild(“Humanoid”) then
hit.Parent:FindFirstChild(“Humanoid”).Health = 0
elseif hit.Name == “Baseplate” then

else
	hit.Material = Enum.Material.CorrodedMetal
		hit.Anchored = false
		wait(1)
		hit.Parent = game.Workspace:WaitForChild("Junk")
end

end

local PartFolder = game.Workspace:WaitForChild(“Junk”)

–add parts with similar properties in the same folder
–or use CollectionService to organize them together
–looping through the entire game isn’t efficient!
local parts = PartFolder:GetChildren()

for i, part in pairs(parts) do
–you can put code in here that will run once for each part.
part.Touched:Connect(touched)
end
end

1 Like

You don’t need to perform this in a while true do loop.

function touched(hit)
	if hit.Parent:FindFirstChild("Humanoid") then
		hit.Parent:FindFirstChild("Humanoid").Health = 0
	elseif hit.Name == "Baseplate" then
	else
		hit.Material = Enum.Material.CorrodedMetal
		hit.Anchored = false
		task.wait(1)
		hit.Parent = workspace:WaitForChild("Junk")
	end
end

local PartFolder = workspace:WaitForChild("Junk")
local parts = PartFolder:GetChildren()

for i, part in ipairs(parts) do
	part.Touched:Connect(touched)
end

True i just noticed that as i was making this post.

Well having a tonne of unanchored parts all over the floor isn’t going to be easy to process for the physics engine
Surely reduce the amount and maybe just destroy an object after a period of time.

and as @Forummer said connecting loads of events, destroys memory

2 Likes
parts.ChildAdded:Connect(function(child)
	child.Touched:Connect(touched)
end)

If children are being added to the “parts” folder you can connect the callback to their Touched event like this avoiding the use of a loop.

1 Like

Its there because the old system used for the touch events destroyed the game it was a script in every single part but somebody helped find a better way.

No, just in general connecting so many events will destroy your game so don’t use the while do loop and remove it since there’s no need to connect so many.

As @Forummer said I there is no need for any loops but there’s a function I forgot existed XD but it works and I’m testing out the solutions.