Make a function called save player data that gets the IntValues/NumberValues and takes a player as a parameter. It should then take those values and save them.
Run this function when a player leaves (connect to Players.PlayerRemoving)
Run this function when the server ends for every player (use game:BindToClose)
Run this function for every player every 5 mins or so (while loop at the end of your code or in a spawn() with a wait(5*60) to yield)
Ok so, here’s a script that shows you how you should save/load things with data store service
local dataStore = game:GetService("DataStoreService")
local moneys = dataStore:GetDataStore("Moneys")
game.Players.PlayerAdded:Connect(function(plr)
local folder = Instance.new("Folder",plr)
folder.Name = "leaderstats"
local value = Instance.new("IntValue",folder)
value.Name = "Money"
local data
local success,err = pcall(function()
data = moneys:GetAsync("Money-"..plr.UserId)
end)
if data and success then
value.Value = data
else
warn(err)
end
end)
game.Players.PlayerRemoving:Connect(function(plr) -- if a player leaves
if plr:FindFirstChild("leaderstats") then
local toSave = plr:FindFirstChild("leaderstats").Money
local data
local success, err = pcall(function()
data = moneys:SetAsync("Money-"..plr.UserId,toSave.Value)
end)
if success then
print("Successfully saved player data")
else
warn(err)
end
end
end)
game:BindToClose(function() -- just in case if the server closes before the script can save the player data
for _, player in pairs(game.Players:GetPlayers()) do
if player:FindFirstChild("leaderstats") then
local toSave = player:FindFirstChild("leaderstats").Money
local data
local success, err = pcall(function()
data = moneys:SetAsync("Money-"..player.UserId,toSave.Value)
end)
if success then
print("Successfully saved player data")
else
warn(err)
end
end
end
end)
while wait(500) do -- if you want auto save
for _, player in pairs(game.Players:GetPlayers()) do
if player:FindFirstChild("leaderstats") then
local toSave = player:FindFirstChild("leaderstats").Money
local data
local success, err = pcall(function()
data = moneys:SetAsync("Money-"..player.UserId,toSave.Value)
end)
if success then
print("Successfully saved player data")
else
warn(err)
end
end
end
end