Attempt to Index nil with Backpack

  1. What do you want to achieve?
    I want to give a sword to the player upon touching a part, but check to see if they have a sword first. If they do, then don’t give them the sword.
  2. What is the issue?
    " Workspace.Part.Script:9: attempt to index nil with ‘Backpack’ "
    Here is the script:
script.Parent.Touched:Connect(function(hit)
	local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
	if player then
		if player.Backpack:FindFirstChild("ClassicSword") == nil then --this is line 4
		end
	else
		local sword = game.ReplicatedStorage.ClassicSword
		local swordClone = sword:Clone()
		swordClone.Parent = player.Backpack --this is line nine
	end
end)

I’m not sure what is wrong with line nine. I suspect that something goes wrong in the beginning of the “if” statement but I’m not sure.
3. What solutions have you tried so far?
Well the original script didn’t have “== nil” on line 4, so I thought that was the issue at first. But I added that and it still isn’t working. I looked at similar posts to mine on the dev forum but all of them had different issues than mine, whether it be the wrong script type, not defining player, etc. I didn’t see my specific issue in them. I might be overlooking something really obvious though.

If player is nil, then it will go to this line. Since player is nil, it can’t find backpack and errors.

I checked and you’re right, player is nil. I don’t know why though, the variable works fine in the beginning of the script

after the else it means it will run if the player is nil, you need to put it before the else.

Sorry, I’m not sure what you mean. Put what before the else?

couldn’t you just use local player = game:GetService('Players').LocalPlayer instead when the part is touched?

I don’t think I can use LocalPlayer in a server script, unless it’s different when you’re using it with the players service

script.Parent.Touched:Connect(function(hit)
	local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
	if player then
        if not player.Backpack:FindFirstChild("ClassicSword") and not hit.Parent:FindFirstChild("ClassicSword") then
		   local sword = game.ReplicatedStorage.ClassicSword
		   local swordClone = sword:Clone()
		   swordClone.Parent = player.Backpack --this is line nine
        end
	end
end)
2 Likes

Thank you, very much appreciated! Does this work because it’s also checking the character?

1 Like