Parts with the same name not deleting

I am trying to make a gun mag removing script that removes all cloned mags in the workspace, so that my game performs better but my script does not work. I have the script in ServerScriptService. Can someone help me?

This is what I tried.

while wait(30) do
	print("yes")
	for i, v in pairs(workspace:GetChildren()) do
		if v.Name =="Mag" then
			print("found")
			v:Destroy()
			print("removed")-- add the player to the table
		end
	end
end


The usual solution to this is using Debris or a coroutine to set a time on creation for when that mag will be deleted:

local Debris = game:GetService("Debris")

-- ...

local mag = -- wherever you JUST created the mag

Debris:AddItem(mag, 30)
-- now this mag will go away on its own in 30 seconds

This way, you won’t have to worry about lag spikes if you happen to delete a lot of mags at the same time.

The issue with this is you’re using pairs, which relies on the contents of the table not changing during iteration. (Which when you destroy an element, the contents change) To fix this issue, iterate through the table backwards in order to prevent any issues with the table elements being deleted.

Show Code
while wait(30) do
	print("yes")
    local children = workspace:GetChildren()
	for i = #children, 1, -1 do
        local child = children[i]
		if child.Name == "Mag" then
			print("found")
			child:Destroy()
			print("removed")
		end
	end
end

Also note that this will only work for direct children of the workspace. If you’re wanting to delete them as any descendant, you’ll have to use GetDescendants. As a better solution, you could also use CollectionService to tag them, then delete them.