I have the following code in my Roblox game:
local DataStoreService = game:GetService("DataStoreService")
local myDataStore = DataStoreService:GetDataStore("myDataStore")
function saveCurrentStats(player)
print("saveCurrentStats")
local success, errormessage = pcall(function()
myDataStore:SetAsync(player.UserId.."-foundcats", player.FoundCats.Value)
end)
if success then
print("Progress successfully saved")
else
print("Error while saving progress")
warn(errormessage)
end
print("saveCurrentStats done")
end
game.Players.PlayerRemoving:Connect(function(player)
saveCurrentStats(player)
end)
Often this works - the data is saved for the player. But quite often I also only get something like this in the output:
18:18:38.708 saveCurrentStats - Server - Script:66
So I get neither if nor else printout (and the data is also indeed not saved)
Is there something I should do to make this robust? Like wait for something at some point.
Problem started to happen more often when my project grew, and the reason is that when running the game from Roblox Studio the script is just terminated when you hit the stop button. It will not be given time to execute, and with a larger project the chance of running the script decreases.
A work-around is to type this in the command bar instead of pressing the stop button:
game:GetService("Players").LocalPlayer:Kick()
This allows you to run the script properly when testing the game in Roblox Studio. When running the game live the issue is not seen, since then the script execution is not terminated prematurely.