Attempt to index nil with Backpack?

Hello,

I really don’t know what’s wrong with my script, it keeps saying “Attempt to index nil with Backpack”.

Here’s my script.

function GiveSword(PlayerObject)
	local ClassicSword = (game:GetService("Lighting"):FindFirstChild("ClassicSword"):Clone())
	if not PlayerObject.Backpack:FindFirstChild("ClassicSword") then
		ClassicSword.Parent = (PlayerObject.Backpack)
	else
		--
	end
end

function RemoveSword(PlayerObject)
	if PlayerObject.Backpack:FindFirstChild("ClassicSword") then
		PlayerObject.Backpack:FindFirstChild("ClassicSword"):Destroy()
	else
		--
	end
end

script.Parent.Touched:Connect(function(Hit)
	local Player = (game:GetService("Players"):FindFirstChild(Hit.Parent.Name))
	wait(0.5)
	GiveSword(Player)
end)

script.Parent.TouchEnded:Connect(function(Hit)
	local Player = (game:GetService("Players"):FindFirstChild(Hit.Parent.Name))
	wait(0.5)
	RemoveSword(Player)
end)
2 Likes

Is that server or local sided?

1 Like

Serversided, I don’t think you can use Part.Touched functions in a local script.

1 Like
function GiveSword(PlayerObject)
	local ClassicSword = (game:GetService("Lighting"):FindFirstChild("ClassicSword"):Clone())
	if not PlayerObject.Backpack:FindFirstChild("ClassicSword") then
		ClassicSword.Parent = (PlayerObject.Backpack)
	else
		--
	end
end

function RemoveSword(PlayerObject)
	if PlayerObject.Backpack:FindFirstChild("ClassicSword") then
		PlayerObject.Backpack:FindFirstChild("ClassicSword"):Destroy()
	else
		--
	end
end

script.Parent.Touched:Connect(function(Hit)
	if Hit.Parent:FindFirstChild("Humanoid") then
        local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
        if Player ~= nil then
            GiveSword(Player)
        end
    end
end)

script.Parent.TouchEnded:Connect(function(Hit)
    if Hit.Parent:FindFirstChild("Humanoid") then
        local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
        if Player ~= nil then
            RemoveSword(Player)
        end
    end
end)
3 Likes

Ohh true wait- It’s GetPlayerFromCharacter… Not FindFirstChild! I’m dumb.

1 Like