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

Remove gear from backpack on touch?

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.

1 comment

0

Are you using a Local or regular script?

3 answers

✓ Accepted answer

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)

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.

1 comment

0

The way to check if the hit is a player is add "if Player then" to your script

-- 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)

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