Cannot destroy folder's children

Wow so many posts in one day…

Anyways in my recent project, I’m working on a sell system except when I try to destroy some parts inside a folder after they touch the sell block, it only gives me the money but doesn’t destroy the parts.

Script

local part = game.Workspace:WaitForChild("SellPart")
local player = game.Players.LocalPlayer
local plr = game.Players.LocalPlayer.Character

local folder = plr:FindFirstChild("headContainer") -- This is the folder inside the player's character

local function sell()
	folder:GetChildren():Destroy()
end

part.Touched:Connect(sell)

And this is the error I get…
Workspace.dummycide.LocalScript:10: attempt to call a nil value
(The line number is different here because I deleted a few lines but it’s talking about the folder:GetChildren():Destroy() line.)

You need to use loops.

for i, v in pairs(folder:GetChildren()) do
    v:Destroy()
end
4 Likes

Building onto the previous post, GetChildren() returns a table full of all the parts inside the object, think of it like selecting everything inside of a model on the explorer.

But it’s only a plain table, so it doesn’t have those functions built in to it. That’s why you need to loop through the table with a pairs/ipairs loop.

local parts = {workspace.Part1,workspace.Part2}
— you couldn’t call :Destroy() on parts because it doesn’t exist on that table.

If you absolutely wanted to be able to call it like that, you could use object-oriented programming with meta tables.

Example: (should work)

local GetChildren = function(object)
    local children = object:GetChildren()
    return setmetatable({},{
        __index = function(tbl,method)
            return function(self,callback)
                for _,obj in pairs(children) do
                    obj[method](obj)
                    if callback then
                        task.spawn(callback,obj)
                    end
                end
            end
        end
    })
end

GetChildren(workspace.Part1):Destroy()

— can call any function on it too (also added new function) 

GetChildren(workspace.Part1):Clone(function(object)
    object.Parent = workspace
    object.Name = "clone"
end)