I’m trying to save the data of a player outside the server but I can’t seem to get it to work.
Here’s the code, (the one in comment form is what I added)
local AUTO_SAVE = true -- Make true to enable auto saving
local TIME_BETWEEN_SAVES = 120 -- In seconds (WARNING): Do not put this lower than 60 seconds
local PRINT_OUTPUT = false -- Will print saves and loads in the output
local SAFE_SAVE = false -- Upon server shutdown, holds server open to save all data
---------------------------------
local players = game:GetService("Players")
local dataStoreService = game:GetService("DataStoreService")
local leaderboardData = dataStoreService:GetDataStore("CurrencyGAMING-00000500")
local function Print(message)
if PRINT_OUTPUT then print(message) end
end
--local Players = game:GetService("Players")
--local cache = {}
--local function getUserIdFromUsername(name)
--if cache[name] then return cache[name] end
-- local player = Players:FindFirstChild(name)
---- if player then
-- cache[name] = player.UserId
-- return player.UserId
-- end
-- local id
-- pcall(function ()
-- id = Players:GetUserIdFromNameAsync(name)
-- end)
-- cache[name] = id
-- return id
--end
--local function updatePlayerDataFromServer(player, bgName, val)
-- local id = getUserIdFromUsername(player)
-- leaderboardData:UpdateAsync(id, {bgName, val})
--end
--game.ReplicatedStorage.DevOnlyUpdateShopOutsideServer.OnServerEvent:Connect(function(player, targetPlayer, bgName, Value)
---- updatePlayerDataFromServer(targetPlayer, bgName, Value)
--end)
local function SaveData(player)
if player.userId < 0 then return end
player:WaitForChild("Currency")
wait()
local Currency = {}
for i, stat in pairs(player.Currency:GetChildren()) do
table.insert(Currency, {stat.Name, stat.Value})
end
leaderboardData:SetAsync(player.userId, Currency)
end
local function LoadData(player)
if player.userId < 0 then return end
player:WaitForChild("Currency")
wait()
local leaderboardStats = leaderboardData:GetAsync(player.userId)
for i, stat in pairs(leaderboardStats) do
local currentStat = player.Currency:FindFirstChild(stat[1])
if not currentStat then return end
currentStat.Value = stat[2]
end
end
players.PlayerAdded:connect(LoadData)
players.PlayerRemoving:connect(SaveData)
if SAFE_SAVE then
game.OnClose = function()
for i, player in pairs(players:GetChildren()) do
SaveData(player)
end
wait(1)
end
end
while AUTO_SAVE do
wait(TIME_BETWEEN_SAVES)
for i, player in pairs(players:GetChildren()) do
SaveData(player)
end
end