Error when trying to give local player sword when part is touched (Attempt to index with nil Backpack)

Hello, I’m currently making a script that would give you a tool when touched. When I do touch the part an error appears, (Attempt to index nil with Backpack) Not sure what the issue is, I looked on Google for some answers, but it didn’t work.

local tool = game.Workspace.SwordFolder.ClassicSword
local player = game.Players.LocalPlayer
local character = player.Character

–//script
script.Parent.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild(“Humanoid”) then
print(“Humanoid Found”)
local klone = tool:Clone()
–//Error
klone.Parent = player.Backpack
if player.character.Humanoid.WalkSpeed == 25 then
player.character.Humanoid.WalkSpeed = 16
end
end
end)

This script isn’t local and it’s placed inside of the part. Just tell me if I did something wrong or I just missed something and I’m that I am being an idiot, thanks!

1 Like

Just realized I copy and pasted the locals twice, my bad.

This script is not local (as you said) so game.Players.LocalPlayer won’t work and that’s why it says nil for backpack

Thanks for the response, how would I find the player’s backpack in a regular script then?

local tool = game.Workspace.SwordFolder.ClassicSword

–//script
script.Parent.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild(“Humanoid”) then
print(“Humanoid Found”)
local klone = tool:Clone()
–//Error
klone.Parent = game.Players:GetPlayerFromCharacter(hit.Parent):WaitForChild("Backpack")
if game.Players:GetPlayerFromCharacter(hit.Parent).character.Humanoid.WalkSpeed == 25 then
game.Players:GetPlayerFromCharacter(hit.Parent).character.Humanoid.WalkSpeed = 16
end
end
end)

You can find the player using local player = game.Players:GetPlayerFromCharacter(hit.Parent) and then the backpack can be easily founded by player.Backpack
I’ve edited your script try it once

3 Likes

Thank you very much, this was the solution.

1 Like