I want to save a global table “Jogo” only when the user exits the game.
For that I have in my Server Script:
local DataStoreService = game:GetService("DataStoreService")
local Jogo = {} -- any data inside the dictionary
game.Players.PlayerRemoving:Connect(function(Player)
local JogoStore = DataStoreService:GetDataStore("Jogo", Player)
print("before") -- working
JogoStore:SetAsync("Jogo", Jogo)
print("after") -- "after" will not print
end)
Weirdly, the print("after") is not running, as well as the new “Jogo” table is not being saved.
Does this have anything to do with me testing inside the Studio?
What’s happening?
Repro
Open this project in Studio: testes.rbxl (21.1 KB)
Firstly, when you are doing tests in Studio, the table might not save. For me, data only saves when there’s something to overwrite not when the game have to create new position of data (for example in the table). Try publishing your game and then play it and it should save.
If you are saying that I can’t save to DataStore inside Studio, I have to disagree, because I was using DataStore2 until now and it was saving everything, even in Studio… but due a Roblox internal bug, I’m trying to use the native DataStore…
I think I found an intermediate solution, but I couldn’t understand:
local DataStoreService = game:GetService("DataStoreService")
local Jogo = {a = 1} -- any data inside the dictionary
game.Players.PlayerRemoving:Connect(function(Player)
local JogoStore = DataStoreService:GetDataStore("Jogo", Player)
print("before PlayerRemoving SetAsync") -- working
JogoStore:SetAsync("Jogo", Jogo)
print("after PlayerRemoving SetAsync") -- "after" will not print
end)
game:BindToClose(function()
print("BindToClose before wait(3)")
wait(3)
print("BindToClose before wait(3)")
end)
This will work:
Also, if I decrease the wait time, it will not work again.
So, it seems I have to force the game to wait 3 seconds in order to save the data…
Can anyone explain why?
PlayerRemoving doesn’t typically work with normal datastores, because the server shuts down before it’s able to save (in-studio). game:BindToClose is the better option for saving with normal datastores (when it comes to studio). In-game, PlayerRemoving successfully fires and saves data
I’m NOT saying that you can’t. I’m saying that it doesn’t work for me when I want Data Stores to create new data. I have to play the game not in Studio, it creates the data and then when I join Studio game, the new data is loaded even if it wasn’t before.
It seems the most reliable code to save the player’s data when the player exits the game (and make it work within Studio), I should do something like:
game.Players.PlayerRemoving:Connect(function(Player)
local JogoStore = DataStoreService:GetDataStore("Jogo", Player)
JogoStore:SetAsync("Jogo", Jogo)
end)
game:BindToClose(function() -- (only needed inside Studio)
if RunService:IsStudio() then -- (only needed inside Studio)
wait(3) -- this will force the "SetAsync" above to complete
end
end)