Clearing Players backpack

Hi. I am trying to get rid of a tool after they use it. I am using a server script inside of a part. Here is the script.

S = script.Parent.Sound
script.Parent.Touched:connect(function ( p )
if p.Parent.Name == “Yellow Key” then

	S:Play()
	script.Parent:Destroy()

– here is what im trying to do. After the door is destroyed, or before, the tool is destroyed. When I tried just doing p:Destroy(), the tool would destroy, but it would remain in the players backpack

I had to make the p in the function spaced out as it made this symbol (p)

Maybe try this instead:

-- ServerScript inside of your BasePart
-- Set the sound's PlayOnRemove property to 'true'

local connection

local function Destroy()
    connection:Disconnect()
    script.Parent:Destroy()
end

connection = script.Parent.Touched:Connect(function(hit)
    local player = game.Players:GetPlayerFromCharacter(hit.Parent)
    if player then
        if player.Backpack:FindFirstChild("Yellow Key") then
            player.Backpack["Yellow Key"]:Destroy()
            Destroy()
        elseif player.Character:FindFirstChild("Yellow Key") then
            player.Character["Yellow Key"]:Destroy()
            Destroy()
        end
    end
end)

If you come across an error with this, let me know. This method was not tested.

1 Like

Ok, give me a second. Im putting it into studio now

Ok, it works. I am personally gonna change it to the players character and not backpack so it opens when they are holding it, Thanks a million

2 Likes

I do not think you need that much code just to clear a players backpack. You can easily clear it with player.Backpack:ClearAllChildren()

script.Parent.Touched:Connect(function(hit)
	local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
	plr.Backpack:ClearAllChildren()
end)
1 Like

OP wants to check if the player has the “Yellow Key” in their inventory. If the player does, the key itself will be destroyed, along with the object that was touched.

Your method will clear every tool in their backpack whenever they touch that brick, regardless whether or not they have the proper key.

So he wants it to clear only a certain tool than every tool?

Exactly. I only want it to clear a certain tool

1 Like

If he has the right tool in his inventory, yes. At least that is what it seems according to his post.

2 Likes