Currency not saving after new game

Hello! I made a currency system for my game but for some reason after you rejoin the game the currency resets back to 0. Does anyone know what is wrong with my script? Is there a better Save and LoadData method?

My Script
local DataStore = game:GetService("DataStoreService"):GetDataStore("Stuff1")


game.Players.PlayerAdded:connect(function(Player)

  LoadData(Player)

end)

game.Players.PlayerRemoving:connect(function(Player)
SaveData(Player)
end)

function SaveData(Player)
  local Stuff = Player:WaitForChild("PlayerSaves"):GetChildren()
  for i=1,#(Stuff) do
    local valuesToSave = {Stuff[i].Value}
    local key = "user_" .. Stuff[i].Name
    DataStore:SetAsync(key, valuesToSave)
    print("Succesfully saved")
	break
  end
end


function LoadData(Player)
  local Stuff = Player:WaitForChild("PlayerSaves"):GetChildren()
  for i=1,#(Stuff) do
    local key = "user_" ..Stuff[i].Name
    local savedValues = DataStore:GetAsync(key)
    local valuesToSave = {Stuff[i].Value}
    if savedValues then
      Stuff[i].Value = savedValues[1]
	  print("Succesfully loaded")
	  break
    else
      SaveData(Player)
    end
  end
end


function SaveAll()
for _,Player in pairs(game.Players:GetPlayers()) do
		coroutine.wrap(function()
			SaveData(Player)
		end)()
	end
end

game.OnClose = function()
	print("Game Closing")
	SaveAll()
	print("Done")
end

while wait(60) do
	SaveAll()
end ```
1 Like

For starters, you should have one DataStore for generic Player Data instead of having a DataStore for each stat. The reason for this is that you can easily hit the SetAsync limit.

You need to remove the break as after the first loop, it’ll break and you won’t save anything else. Most likely you’re saving one piece of data, but that’s not your currency.

1 Like

I think you maybe should do that like…

local success,err = pcall(
    DataStore:SetAsync(key, valuesToSave)
)
if success then
    print("Successfully saved!")
else
    print(err)
end

(same with DataStore:GetAsync())
Not sure if it will fix the issue but you can try… :slight_smile:

1 Like

That’s not how you use a pcall in that convention.

local success, err = pcall(DataStore.SetAsync, DataStore, key, valuesToSave)

local success, err = pcall(function ()
    DataStore:SetAsync(key, valuesToSave)
end)

local success, err = pcall(function ()
    return DataStore:SetAsync(key, valuesToSave)
end)

Doesn’t answer OP’s question anyway.

1 Like

Of course,I’ve wrote that on web, in studio I wouldn’t make that fault… :sweat_smile:

I would have to agree here also. I had a very similar predicament.

1 Like