0
votes

I wanted that every time I leftclick/Activate the Tool, a Part gets Destroyed. So I put some Parts in a Folder and made it a Table ("PartTable"). I then proceeded with a function which runs an in pairs loop to delete one Part out of the folder and break. That's because I didn't want one click deleting everything, there is no fun in that. I also made the system print whenever I delete a Part. Against my expectation it just worked once. Only one Part gets deleted, while the system keeps printing, when I click.
Look at me being disappointed

1 local PartTable = game.Workspace.Folder:GetChildren()
2 local Tool = script.Parent
3
4 Tool.Activated:Connect(function()
5   for i, v in pairs(PartTable) do
6       v:Destroy()
7       print("Part deleted")
8       break
9   end
10  end)

I am also like a complete beginner in scripting. Sorry for that

1

1 Answers

0
votes

The problem is that you never update the table after you destroy the first element. On the first run, you destroy the block in the first position in the array, then escape. That first element in the list still refers to the destroyed block, though. On the second run, it "destroys" the same block again, then exits the loop again.

The fix is pretty simple though, you just need to move the table assignment into the tool's Activated connection. This will fetch the updated list of children every time the tool is activated.

local Tool = script.Parent

tool.Activated:Connect(function()
    -- fetch the parts in the folder
    local PartTable = game.Workspace.Folder:GetChildren()

    -- delete one
    if #PartTable > 0 then
        PartTable[1]:Destroy()
    end
end)