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 ```