Attempt to index nil with 'Backpack'

So What I’m trying to do is when the player touches a certain part, It checks to make sure a tool is equipped. If it is, then it fires the rest on server side. But my problem is at the ** mark. GApp is returning nil, even though the item is in the backpack and i dont know why. The script is in a local script in StarterPlayerScripts. Thanks


King.Feed.Touched:connect(function(hit)
	if db then
		print("DB is working")
		db = false
		local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
		local char = hit.Parent

		**local GApp =  player.Backpack:FindFirstChild("GoldenApple")
		local hrp = char:WaitForChild("HumanoidRootPart")
	
		GApp.Equipped:Connect(function()
			print("King Fed")
			game.ReplicatedStorage.AxoFedRE:FireServer(hrp)
		end)
		
		
	end
	wait(2)
	db = true
end)

I believe that the player variable may be nil, and as such trying to do player.Backpack is the same as doing nil.Backpack. This is probably because the touched event is firing on a part which isn’t the player, and since there’s no checks to make sure that it is a player Instance, nothing happens.

I’d recommend changing your code to be as such:

King.Feed.Touched:connect(function(hit)
	if db then
		if not hit.Parent:FindFirstChild("Humanoid") return end -- If there is no humanoid, end 
		local char = hit.Parent -- We can now assume there is a char if we know its a player
		local player = game:GetService("Players"):GetPlayerFromCharacter(char)

		**local GApp =  player.Backpack:FindFirstChild("GoldenApple")
		local hrp = char:WaitForChild("HumanoidRootPart")
	
		GApp.Equipped:Connect(function()
			print("King Fed")
			game.ReplicatedStorage.AxoFedRE:FireServer(hrp)
		end)
		
		
	end
	task.wait(2)
	db = true
end)
1 Like

Yep, you were right, it was not anchored so it kept touching other things. Thanks!