Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Unexpected error when using pairs?

I have a script which, when a part is added to the workspace it'll be destroyed. But, whenever a part is added into the workspace I get this error, in orange; Something unexpectedly tried to set the parent of Part to NULL while trying to set the parent of Part. Current parent is Workspace.

Here is my code;

game.Workspace.DescendantAdded:connect(function()
for _, v in pairs(game.Workspace:GetChildren()) do
		if v.Name == "Part" and v:IsA("Part") then
			v:Destroy()
		end
	end
end)

Any help is appreciated! Thanks! `

1 comment

0

It is better to use v:IsA("BasePart"), since that'll include all Parts.

1 answer

✓ Accepted answer

Add a wait() right after the function.

This error happens because you want to set the parent of something while the parent is being set.

game.Workspace.DescendantAdded:Connect(function()
	wait()
	for _, v in pairs(game.Workspace:GetChildren()) do
		if v.Name == "Part" and v:IsA("Part") then
			v:Destroy()
		end
	end
end)

Also, im not sure why you use DescendantAdded if you're just going to clear out just the top layer from the workspace, and not the descendants. I suppose you want to use the DescendantAdded to find whatever is added. Use this instead:

game.Workspace.DescendantAdded:Connect(function(Object)
	wait()
	if Object.Name == "Part" and Object:IsA("Part") then
		v:Destroy()
	end
end)

1 comment

0

Thanks! And yeah, you're right aha.

This discussion is preserved as it was. New answers, comments, and votes are closed.