Loose part cleanup script

I’ve been developing a game that is mainly based on destroying objects and buildings that are welded together.

  1. What do you want to achieve? Keep it simple and clear!
    I want to make a script that removes loose parts in the workspace that are unanchored and aren’t welded to any other parts after a certain amount of time.
  2. What is the issue? Include screenshots / videos if possible!
    I’ve tried a few times but it hasn’t been working and i don’t know where to start.
  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    It did have a script timeout, assuming because it was trying to get every single part in the workspace, so i tried to fix it, and it got rid of the error but it still doesn’t work.

This is my current script in serverscriptservice.

local debris = game:GetService("Debris")

for _, descendant in pairs(workspace:GetDescendants()) do
	while true do
		if descendant:IsA("BasePart") and descendant.Anchored == false and not descendant.Parent:FindFirstChildOfClass("Humanoid") then
			local welded = descendant:GetConnectedParts(true)
			if #welded == 1 then
				debris:AddItem(descendant, 1)
			end
		end
		wait(10)
	end
end

Does the script work for a while when play testing the game at first, or it doesn’t work at all?

Rewrite the code for better readability

also i don’t think you need a while loop if you already got all descendants:

local debris = game:GetService("Debris")

local descendants = game:GetService("Workspace"):GetDescendants()

for i = 1, #descendants do
	local descendant = descendants[i]
	if descendant.ClassName ~= "BasePart" then continue end
	if descendant.Anchored == true then continue end
	if descendant.Parent:FindFirstChildOfClass("Humanoid") then continue end
	
	local welded = descendant:GetConnectedParts(true)
	if #welded == 1 then
		debris:AddItem(descendant, 1)
	end
end

If it still doesn’t work (as in terms of it doesn’t cleanup? then debug the descendant → Use print statements: Example: print(descendant.Name) after detecting that the descendant Parent is not true to the humanoid, Check the welded, print to see any valid response to your if statement)