Attempt to index nil with leaderstats

I am trying to increase a player’s stats when they touch a part. This should be simple, but every solution I have tried results in this exact same error.
image

Below is the current version of my script that made this error

script.Parent.Touched:Connect(function(hit)
	local hum = hit.Parent:FindFirstChild("Humanoid")
	local player = game.Players:GetPlayerFromCharacter(hum)
	local stats = player.leaderstats.Wins
	if hit and hit.Parent and hit.Parent:FindFirstChild("HumanoidRootPart") then
		hit.Parent.HumanoidRootPart.Position = Vector3.new(0.06, 1.2, -29.08)
		stats.Value = stats.Value + 1
	end
end)
script.Parent.Touched:Connect(function(hit)
	local hum = hit.Parent:FindFirstChild("Humanoid")
	local player = game.Players:GetPlayerFromCharacter(hum.Parent)
	local stats = player.leaderstats.Wins
	if hit and hit.Parent and hit.Parent:FindFirstChild("HumanoidRootPart") then
		hit.Parent.HumanoidRootPart.Position = Vector3.new(0.06, 1.2, -29.08)
		stats.Value = stats.Value + 1
	end
end)

this?
Attempt to index nil means that player hasn’t been defined yet most likely.

Edit: Line 3 is from AsciiSalt’s suggestion.

1 Like

Hey you are correct. The reason why he’s getting that error is because his variable “Player” is nil.

All he really needed to do

local player = game.Players:GetPlayerFromCharacter(hum.Parent)

since the method GetPlayerFromCharacter assumes the first argument is the players character but he was giving it the players Humanoid.

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.