Trouble Saving Data

I am trying to get "cash " to save when the player leaves the game.

This script used to work fine before, i don’t know what is causing it to not save.

local DataStoreService = game:GetService("DataStoreService")

local myDataStore = DataStoreService:GetDataStore("myDataStore")

game.Players.PlayerAdded:Connect(function(player)
   local leaderstats = Instance.new("Folder")
   leaderstats.Name = "leaderstats"
   leaderstats.Parent = player

   local cash = Instance.new("IntValue")
   cash.Name = "Cash"
   cash.Parent = leaderstats
    
   local data
   local success, errormessage = pcall(function()
       data = myDataStore:GetAsync(player.UserId.."-cash")
   end)
   
   if data ~= nil then
	   cash.Value = data
   else
       print("Cant collect data")  
    end
end)

game.Players.PlayerRemoving:Connect(function(player)

   local success, errormessage = pcall(function()
       myDataStore:SetAsync(player.UserId.."-cash",player.leaderstats.Cash.Value)
   end)
   if success then
	    print("Data Was Saved")
      warn(errormessage)
   else
	    print("Something is Wrong")
      warn(errormessage)
   end
end)

Are there any errors? It looks fine. Maybe avoid taking data directly from a leaderstat? I recommend looking into the DataStore2 module as it’s more secure, protected, and easier to use.

2 Likes

Make sure you are testing this in game and not in studio testing. Set async tends to not work inside of studio test. I would also recommend saving that data for all players over regular intervals. Also make sure that Studio has access to API services is enabled. It is located in game settings.

3 Likes