I want to give and remove a sword from a player when they enter a box how can I do this?
here’s my code:
local character = hit.Parent
local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
if character:FindFirstChild("Humanoid") then
for i, v in pairs(game.ReplicatedStorage:GetDescendants()) do
if v:IsA("Tool") and v.Name == "ClassicSword" then
v.Parent = plr.Backpack
else
end
end
end
end)
script.Parent.TouchEnded:Connect(function(hit)
local character = hit.Parent
local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
if character:FindFirstChild("Humanoid") then
for i, v in pairs(plr.Backpack:GetDescendants()) do
if v:IsA("Tool") and v.Name == "ClassicSword" then
v.Parent = game.ReplicatedStorage
else
end
end
for i, v in pairs(character:GetDescendants()) do
if v:IsA("Tool") and v.Name == "ClassicSword" then
v.Parent = game.ReplicatedStorage
else
end
end
end
end)```
First you need to check if whatever hit your part is actually a humanoid, before getting the plr otherwise you might get an error if something other than a player hits it.
You also want to clone the sword instead of doing that as it is much more efficient.
local debounce2 = false
local sword = nil
script.Parent.Touched:Connect(function(hit)
if not debounce2 then
debounce2 = true
local hum = hit.Parent:FindFirstChild("Humanoid")
if hum and not debounce then
debounce = true
local s = game.ReplicatedStorage.ClassicSword:Clone()
s.Parent = hit.Parent
sword = s
end
debounce2 = false
end
end)
script.Parent.TouchEnded:Connect(function(hit)
if not debounce2 then
debounce2 = true
local hum = hit.Parent:FindFirstChild("Humanoid")
local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
if hum and debounce then
debounce = false
sword:Destroy()
end
debounce2 = false
end
end)```
this is the problem:
https://imgur.com/a/x75b5wI
You are missing a lot of code in that snippet. I don’t see where you declare the variable “sword” either. Are you sure you sent the entire code snippet?