Could anyone tell me why I can't access this value in the backpack?

Hello there, I was working on a script that allows Server-Sided script access to the player’s backpack containing an IntValue inside. I keep getting an error saying

Workspace.WaterStun1.Script:8: attempt to index nil with ‘WaterStun’

Could anyone help me determine the issue? If so, thanks!

Here’s my script:

script.Parent.Touched:Connect(function(hit)
local humanoid = hit.Parent:FindFirstChild(“Humanoid”)

if humanoid then
local player = hit.Parent
local BP = player:FindFirstChild(“Backpack”)

  if BP:WaitForChild("WaterStun", 0.05) then
  	
  	print("They have a stun value")

end

end
end)

Wrong category. As for your error its because hit.Parent is not the player instance but rather the players character model in workspace.

You should instead use :GetPlayerFromCharacter.

E.g

local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)

if player then -- check if player exist
-- do whatever else here
end

Note that I’m on mobile so there may be typos.

1 Like
local Players = game:GetService("Players")
local Part = script.Parent

Part.Touched:Connect(function(Hit)
	local HitModel = Hit:FindFirstAncestorWhichIsA("Model")
	if HitModel then
		local HitPlayer = Players:GetPlayerFromCharacter(HitModel)
		if HitPlayer then
			local Backpack = HitPlayer:FindFirstChild("Backpack")
			if Backpack then
				local WaterStun = Backpack:FindFirstChild("WaterStun")
				if WaterStun then
					--Do code here.
				end
			end
		end
	end
end)

Just to extend on what’s already been stated use the instance method “:FindFirstChild()” to verify the existence of an instance not “WaitForChild()”. I’ve also made a slight improvement which will allow for the BasePart instances named “Handle” found in all accessories worn by player’s characters to trigger the “Touched” event.