PLEASE remember to wrap SetAsync and GetAsync in a pcall().
local ds = game:GetService("DataStoreService"):GetDataStore("Save")
game.Players.PlayerAdded:Connect(function(plr)
wait()
local plrkey = "id_"..plr.userId
local save1 = plr.leaderstats.Coins
--local save2 = plr.leaderstats.Cash
local GetSaved, err = pcall(function()
ds:GetAsync(plrkey)
end)
if GetSaved then
save1.Value = GetSaved[1]
--save2.Value = GetSaved[2]
elseif err then
error(err)
else
local NumberForSaving = {save1.Value} --save2.Value}
local success, err = pcall(function()
ds:GetAsync(plrkey)
end)
if success then
print("successfully retrieved value")
elseif err then
print(err)
end
end
end)
game.Players.PlayerRemoving:Connect(function(plr)
local function setValue()
ds:SetAsync("id_"..plr.userId, {plr.leaderstats.Coins.Value})--, --plr.leaderstats.Cash.Value})
end
local success, err = pcall(function()
setValue()
end)
if success then
print("successfully saved")
elseif err then
print(err)
setValue()
end
end)
You should use :WaitForChild() when getting the player’s leaderstat values, as you don’t know if they have already been created when PlayerAdded fires.
Also have a loop that saves data every few seconds/minutes. Only saving data on player leave is often good enough but imagine a player playing for 2 hours non-stop. If the server crashes, the Player removing signal won’t fire and their data won’t be saved. Losing progress isn’t fun for players.