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

How do I remove a tool in the backpack without error?

I want this when clicking the text button even if the tools are not in the Backpack, the Script continues without errors, and if one or all of the tools are in the Backpack are destroyed.

If you did not understand my explanation, here's a makeshift script:

local player = game:GetService("Players").LocalPlayer
local bp = player:findFirstChild("Backpack")

script.Parent.MouseButton1Click:connect(function() 

        bp.Tool:Destroy()
		bp.Tool2:Destroy()
		bp.Tool3:Destroy()
		bp.Tool4:Destroy()

--script continuation...
end)

2 answers

✓ Accepted answer

If you just want to empty the backpack, you can do

backpack:ClearAllChildren()

But if you want to remove a specific tool only if it exists, use FindFirstChild() and check if it returns nil

local tool = backpack:FindFirstChild("Tool1")
if tool then
    tool:Destroy()
end

And for multiple tools:

local tools = {"Tool1", "Tool2", "Tool3"}
for i,v in pairs(tools) do
    local tool = backpack:FindFirstChild(v)
    if tool then
        tool:Destroy()
    end
end

2 comments

0

Line 4 you wrote hen instead of then.

0

Yea sorry, hard to script on phone

If you're asking to effectuate the code you've written, and if it errors keep going in the script, you may want to wrap your code in a pcall(). This will make a protected call which, when the script errors it will let it continue.

local player = game:GetService("Players").LocalPlayer
local bp = player:findFirstChild("Backpack")

script.Parent.MouseButton1Click:connect(function() 
	pcall(function() -- this will make an anonymous pcall function
		bp.Tool:Destroy()
		bp.Tool2:Destroy()
		bp.Tool3:Destroy()
		bp.Tool4:Destroy()
	end)
	--script continuation...
end)

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