Attempt to index nil with leaderstats

hey, just ran into a problem. working on my game, but everytime I click it says “attempt to index nil with leaderstats” heres the code, I did provide the line that the error happens.

local dss = game:GetService("DataStoreService")
local data = dss:GetDataStore("data")


game.Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder",player)
	leaderstats.Name = "leaderstats"
	
	local Hats = Instance.new("IntValue",leaderstats)
	Hats.Name = "Hats Collected"
	Hats.Value = data:GetAsync(player.UserId) or 0
	local never = false
	game.Workspace.LargeTasseledScarf.Handle.ClickDetector.MouseClick:Connect(function(E)
		if not never then
			never = true
			local player = game.Players:GetPlayerFromCharacter(E.Parent)
			player.leaderstats["Hats Collected"].Value = player.leaderstats["Hats Collected"].Value + 1 -- here is the error
			wait(math.huge)
			never = false
		end
	end)
end)

game.Players.PlayerRemoving:Connect(function(player)
	data:SetAsync(player.UserId, player.leaderstats["Hats Collected"].Value)
end)
1 Like

why are you doing player.leaderstats when leaderstats is already defined?

1 Like

well, I guess my brain wasn’t working then. haha thanks!

1 Like