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

Remove gear from backpack on touch?

Asked by 5 years ago

It's pretty self explanatory. When the block is touched, a certain gear is removed from the player's backpack (in this case "Sword"). This is the script I was using :

parent = script.Parent

function onTouch(hit)
game.Players.Player.Backpack.Sword:remove()
end

parent.Touched:connect(onTouch)

Not sure what has gone wrong in the script.

0
Are you using a Local or regular script? s_iara 94 — 5y

3 answers

Log in to vote
0
Answered by
Syclya 224 Moderation Voter
5 years ago

I have improved your code a bit, this should be the solution.

local Name = "name of tool" -- name of the tool

script.Parent.Touched:Connect(function(hit)
    local Player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
    if Player then
        local Backpack = Player:FindFirstChild("Backpack")
        if Backpack then
            if Backpack:FindFirstChild(Name) then -- if found, destroy it
                Backpack[Name]:Destroy()
            end
        end
    end
end)
Ad
Log in to vote
1
Answered by 5 years ago
Edited 5 years ago

game.Players.Player is nothing, unless you are magically called Player, it won't work.

You'll need to search the player from the hit part: https://developer.roblox.com/en-us/api-reference/function/Players/GetPlayerFromCharacter

Note that hit is a part of your character body in case you're touching it, but the hit part can be any part in the game. So make sure after calling GetPlayerFromCharacter that you make sure it actually is a player and not nil.

0
The way to check if the hit is a player is add "if Player then" to your script itchymoonfire 179 — 5y
Log in to vote
0
Answered by 5 years ago
Edited 5 years ago
-- LocalScript

local part = script.Parent

function onTouch(hit)
local plr = game.Players.LocalPlayer
if plr.Backpack:FindFirstChild("Sword") ~= nil then -- Checks if Sword is not equipped by the player
 plr.Backpack:FindFirstChild("Sword"):Destroy()
else if workspace:FindFirstChild(plr.Name):FindFirstChild("Sword") ~= nil then -- Checks if Sword is equipped by the player
 workspace:FindFirstChild(plr.Name).Sword:Destroy()
  end
end

part.Touched:connect(onTouch)

Answer this question