Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Unexpected error when using pairs?

Asked by
awfulszn 394 Moderation Voter
7 years ago

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! `

0
It is better to use v:IsA("BasePart"), since that'll include all Parts. soved 69 — 7y

1 answer

Log in to vote
1
Answered by
RubenKan 3615 Moderation Voter Administrator Community Moderator
7 years ago
Edited 7 years ago

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)
0
Thanks! And yeah, you're right aha. awfulszn 394 — 7y
Ad

Answer this question