DataStore assigns same coins value to every player

Hello!
Today I was working with DataStores, and I ran into an issue. When some other player joins the game, they get the coins value of my character’s datastore. How’s this happening?

The script:

local playersService = game:GetService("Players")
local dataStoreService = game:GetService("DataStoreService")

local coinsData = dataStoreService:GetDataStore("PlayersCoins")

playersService.PlayerAdded:Connect(function(player)
	local success, coinsVal = pcall(function()
		return coinsData:GetAsync(player)
	end)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	
	local coins = Instance.new("IntValue")
	coins.Value = coinsVal or 0
	coins.Name = "Coins"
	
	coins.Parent = leaderstats
	leaderstats.Parent = player
end)

playersService.PlayerRemoving:Connect(function(player)
	local success, err = pcall(function()
		coinsData:SetAsync(player, player.leaderstats.Coins.Value)
	end)
end)

Any help would be appreciated!
Thanking you in advance,
pranvexploder. :smiley:

I recommend using player.UserId instead of just player for your data key, if you just use player it will use the same key for everyone.

5 Likes