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:
01 | local player = game:GetService( "Players" ).LocalPlayer |
02 | local bp = player:findFirstChild( "Backpack" ) |
03 |
04 | script.Parent.MouseButton 1 Click:connect( function () |
05 |
06 | bp.Tool:Destroy() |
07 | bp.Tool 2 :Destroy() |
08 | bp.Tool 3 :Destroy() |
09 | bp.Tool 4 :Destroy() |
10 |
11 | --script continuation... |
12 | end ) |
If you just want to empty the backpack, you can do
1 | backpack:ClearAllChildren() |
But if you want to remove a specific tool only if it exists, use FindFirstChild()
and check if it returns nil
1 | local tool = backpack:FindFirstChild( "Tool1" ) |
2 | if tool then |
3 | tool:Destroy() |
4 | end |
And for multiple tools:
1 | local tools = { "Tool1" , "Tool2" , "Tool3" } |
2 | for i,v in pairs (tools) do |
3 | local tool = backpack:FindFirstChild(v) |
4 | if tool then |
5 | tool:Destroy() |
6 | end |
7 | end |
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.
01 | local player = game:GetService( "Players" ).LocalPlayer |
02 | local bp = player:findFirstChild( "Backpack" ) |
03 |
04 | script.Parent.MouseButton 1 Click:connect( function () |
05 | pcall ( function () -- this will make an anonymous pcall function |
06 | bp.Tool:Destroy() |
07 | bp.Tool 2 :Destroy() |
08 | bp.Tool 3 :Destroy() |
09 | bp.Tool 4 :Destroy() |
10 | end ) |
11 | --script continuation... |
12 | end ) |