It is recommended to use a pcall function when retrieving or saving a players data, a pcall stands for a “Protected Call”, you can learn more about it here: Pcalls
the reason why we use them in datastores is because Roblox servers sometimes tend to shutdown/go down, and usually that can also have an impact on datastores. If there’s no datastore to fetch data from, then the function will give an error, consequently also stopping the rest of the script from continuing. So use a pcall for both GetAsync()
and SetAsync()
Another thing I recommend is to save their data manually when using game:BindToClose
. Ofcourse, what you did does look right, but playeremoving connection when kicking the players during a shutdown might fail, I’d recommend use :SetAsync()
inside the game:BindToClose
function too, we could have a function you can use for both playerRemoving
and game:BindToClose
your code should look something like this:
--Inside PlayerAdded Event
local GetSaved
local success,errormessage = pcall(function()
GetSaved = MyStore:GetAsync(playerKey)
end)
if success then
if GetSaved then
saveValue1.Value = GetSaved[1]
saveValue2.Value = GetSaved[2]
else -- success but the data retrieved is nil, meaning it is a new player.
print(`New Player: {player.Name}`)
end
elseif errormessage then
print(`ERR: {errormessage}`)
end
function savePlayersData(player)
local saveItems = {player.Coins.Value, player.Checkpoint.Value}
local success,errormessage = pcall(function()
MyStore:SetAsync("id_"..player.UserId, saveItems)
end)
if success then
print(`Successfully saved {player.Name}s data!`)
elseif errormessage then
print(`ERR: {errormessage}`)
end
end
game.Players.PlayerRemoving:Connect(savePlayersData)
---bindToClose
game:BindToClose(function()
for i, plr in pairs(game.Players:GetPlayers()) do
savePlayersData(plr)
--plr:Kick("Your data has been saved.")
end
end)
Hope this makes sense, the code you’re using will def work, I am just giving you a better version, in case of large servers, it is important to always use the most efficient way, making no mistakes and making sure that there would be no errors that could stop the rest of the script. Good Luck!