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

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

Asked by 5 years ago

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

Log in to vote
3
Answered by
Amiaa16 3227 Moderation Voter Community Moderator
5 years ago
Edited 5 years ago

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
0
Line 4 you wrote hen instead of then. SCP774 191 — 5y
0
Yea sorry, hard to script on phone Amiaa16 3227 — 5y
Ad
Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

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)

Answer this question