Im trying to setup a datastore for my game. I have the datastore and leaderboard setup but whatever I try I can't get the data to save.
Datastore in ServerScriptService:
local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local playerCoinsStore = DataStoreService:GetDataStore("PlayerCoinsStore")
local playerNotificationEvent = Instance.new("RemoteEvent")
playerNotificationEvent.Name = "PlayerNotificationEvent"
playerNotificationEvent.Parent = ReplicatedStorage
local playerCoins = {}
local function onPlayerAdded(player)
local playerId = tostring(player.UserId)
local success, coins = pcall(function()
return playerCoinsStore:GetAsync(playerId)
end)
if success then
playerCoins[player] = coins
else
playerNotificationEvent:FireClient(player, "Error retrieving saved data: please try again later")
end
-- Do other player initialization code
end
Players.PlayerAdded:Connect(onPlayerAdded)
Leaderboard in ServerScriptService:
local DataStoreService = game:GetService("DataStoreService")
local playerCoinsStore = DataStoreService:GetDataStore("PlayerCoinsStore")
function onPlayerEntered(newPlayer)
local stats = Instance.new("IntValue")
stats.Name = "leaderstats"
local coins = Instance.new("IntValue")
coins.Name = "Coins"
pcall(function(player)
coins.Value = playerCoinsStore:GetAsync("coins")
end)
coins.Parent = stats
stats.Parent = newPlayer
end
game.Players.ChildAdded:connect(onPlayerEntered)
while wait(2) do
for _, player in ipairs(game.Players:GetPlayers()) do
if player:FindFirstChild("leaderstats") then
player.leaderstats.Coins.Value = player.leaderstats.Coins.Value + 1
end
end
end
--Autosave
while wait(5) do
pcall(function(player)
playerCoinsStore:SetAsync("coins", player.leaderstats.coins.Value)
end)
end
Im probably doing something really dumb. I just started learning a few days ago so any help will be appreciated. Thanks!

2 comments
When using pcall, the second variable (coins) is the error. If it was a success, it would be nil. You should use a variable to do it like: pcall(function() coins = ds:GetAsync(key) end)
Don't use ChildAdded on Players service