This is the end of one of mine...set up a little different from yours but perhaps useful. It references "config", a ModuleScript in RS. In the ModuleScript is where it states
SaveOnExit = true and AutomaticSaving = true (every 5 min but you could change that). It also uses BindToClose as you can see to save data if all servers are shutdown.
game.Players.PlayerRemoving:Connect(function(plr)
if (not plr) then return end
pcall(function()
if require(config).SaveOnExit then
SaveData(plr)
end
end)
end)
local ServerTimeout = 5
game:BindToClose(function()
for _,v in pairs(game.Players:GetPlayers()) do
if (v~=nil) then SaveData(v) end
end
wait(ServerTimeout)
end)
Here is a portion ref the leaderstats for SaveData for their Level and Gold. As suggested by incapaz and Enomphia, there is also a Notify remote event in ReplicatedStorage so the server will know when values have been changed client side.
SaveData = function(plr)
pcall(function()
local lstats = plr:FindFirstChild("leaderstats")
if (lstats~=nil) then
local level = lstats:FindFirstChild("Level")
local gold = lstats:FindFirstChild("Gold")
if (level~=nil) and (gold~=nil) then
Stats:SetAsync(plr.UserId,{level.Value,gold.Value})
end
end
1 comment
No, changed events are unnecessary. What if a OP's game has values that constantly change? Less than 6 seconds each time? I'd instead have some auto save interval every 30 seconds-1 minute or so.