Datastore not being saved when rejoining server in Studio

What’s the problem?

I’ve created a script (some people helped me) and the Datastore isn’t working. It says that the value has been saved. Yet, when I rejoin the server (in-studio) it still shows the default amount. No errors are appearing in the Output either. Even the print that states if it’s an error doesn’t print, nor the success print. Anyways here’s the script.

local DSS = game:GetService("DataStoreService")
local Datastore = DSS:GetDataStore("TestDataStore")

game.Players.PlayerAdded:Connect(function(plr)

   local CurrencyData = Instance.new("Folder")
   CurrencyData.Name = "CurrencyData"
   CurrencyData.Parent = plr

   local Balance = Instance.new("NumberValue")
   Balance.Name = "Balance"
   Balance.Parent = CurrencyData
   Balance.Value = 1000

   local success, currentbalance = pcall(function()
      return Datastore:GetAsync(plr.UserId .. "-balance")
   end)
   if success then
      if currentbalance then
           Balance.Value = currentbalance
      end
      print("Success getting data!")
   else
      print("Error getting data!")
   end
end)

game.Players.PlayerRemoving:Connect(function(plr)
   local success, err = pcall(function()
      Datastore:SetAsync(plr.UserId .. "-balance", plr.CurrencyData.Balance.Value)
   end)
   if success then
     print("Success saving data!")
   else
     print("Error saving data!")
   end
end)

**Status**

Solution: No

Use this Function to save data as the game is shutting down. Loop over all the current players in the game and save their data. The Reason Data Might Not Be Saving is because the Player Removing Event is never fired. Using the BindToClose will solve this problem. This Problem most likely would only occur in Studio tho so If you test your current code in a live game it should save.

1 Like

Thanks! The problem was that I was running it inside studio.