Leaderstats index nil error, how to fix?

I didnt notice the number 1, that was my bad.

The error I screenshotted above?

local Players = game:GetService("Players")

Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(character)
		character:WaitForChild("Humanoid").Died:Connect(function()
			local fine = math.random(5,30)
			local leaderstats = player.leaderstats
			local coins = leaderstats:FindFirstChild("coins")
			
			if coins.Value <= fine.Value then
				coins.Value = 0
			else
				coins.Value = coins.Value - fine.Value
			end
		end)
	end)
end)

Please re-name one of these, either the player variable, or the player param, it can cause a confusion to the code.

game:GetService('Players').PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(character)
		character:WaitForChild("Humanoid").Died:Connect(function()
			local fine = math.random(5,30)
			local leaderstats = player.leaderstats --Error located
			local coins = leaderstats:FindFirstChild("coins")
			
			if coins.Value <= fine then
				coins.Value = 0
			else
				coins.Value-=fine
			end
		end)
	end)
	end)

This should work fine

1 Like

Overall, this should be working :

local Players = game:GetService('Players')

Players.PlayerAdded:Connect(function(p)
	p.CharacterAdded:Connect(function(character)
		character:WaitForChild("Humanoid").Died:Connect(function()
			local fine = math.random(5,30)
			local leaderstats = p.leaderstats 
			local coins = leaderstats:FindFirstChild("coins")
			
			if coins.Value <= fine.Value then
				coins.Value = 0
			else
				coins.Value -= fine.Value
			end
		end)
	end)
end)

Changed that to use -= since I feel it’s nicer, also didn’t see you post that script until I posted mine lol

(On mobile)

1 Like

I tried all of your scripts, it works fine but I noticed one detail I forgot to remove.

Theres no Value in fine.Value because it’s a local that generates a random number so once I removed it, it works!

The other thing I learned is that I had to name local’s differently. Thanks guys!

2 Likes

That won’t work actually lol, you are still using .player

When you changed it to be called p

This should work though:

Both scripts will do the exact same thing.

local Players = game:GetService('Players')

Players.PlayerAdded:Connect(function(p)
	p.CharacterAdded:Connect(function(character)
		character:WaitForChild("Humanoid").Died:Connect(function()
			local fine = math.random(5,30)
			local leaderstats = p.leaderstats 
			local coins = leaderstats:FindFirstChild("coins")
			
			if coins.Value <= fine.Value then
				coins.Value = 0
			else
				coins.Value -= fine.Value
			end
		end)
	end)
end)

Glad to hear! Make sure to mark something as solution for future users!

Yes I just wanted to point out that error that you had! Also as OP stated, just remove .Value from the fine variables