I annotated the script to better explain whats going on. This is the way I do it. If you have any questions let me know.
local PlayerSavedStuff = game:GetService('DataStoreService'):GetDataStore("PlayerSaveSystem")
local RunService = game:GetService("RunService")
local db = 3
function SaveTableFunc(player)
local SaveTable = {
Thing1 = player.PlayerSave.thing1.Value,
Thing2 = player.PlayerSave.thing2.Value,
}
return SaveTable
end
game.Players.PlayerAdded:connect(function(player)
repeat wait() until player.Character
repeat wait() until script:FindFirstChild("PlayerSave")
local save1 = script.PlayerSave:Clone()
save1.Parent = player
local PS = player.PlayerSave
local save = SaveTableFunc(player)
local playerkey = "player-"..player.userId
local SaveFiles = PlayerSavedStuff:GetAsync(playerkey)
function dataInput(player, save)
PS.thing1.Value = SaveFiles.Thing1
PS.thing2.Value = SaveFiles.Thing2
print("Got saved data for "..player.Name)
end
local Passed, Error = pcall(function()
if SaveFiles == nil then
print(player.Name.." has no save data yet")
else
dataInput(player, save)
end
end)
if Error then
print("***ERROR GETTING SAVE FILE FOR "..player.Name)
local attempts = 0
while wait(db) do
local retries = attempts + 1
attempts = retries
local pass,err = pcall(function()
if SaveFiles == nil then
print(player.Name.." has no save data yet")
else
dataInput(player, save)
end
end)
if pass or attempts == 5 then break end
end
end
end)
function SaveData(player)
local Success,Error = pcall(function()
local playerkey = "player-"..player.userId
local save = SaveTableFunc(player)
PlayerSavedStuff:SetAsync(playerkey,save)
print("Saved data for "..player.Name)
end)
if Error then
print("***ERROR SAVING DATA FOR "..player.Name)
local attempts = 0
while wait (db) do
local retries = attempts + 1
attempts = retries
local pass,fail = pcall(function()
local playerkey = "player-"..player.userId
local data = SaveData(player)
PlayerSavedStuff:SetAsync(playerkey,save)
print("Successfully saved data for "..player.Name)
end)
if pass or attempts == 5 then break end
end
end
end
game.Players.PlayerRemoving:Connect(SaveData)
game:BindToClose(function()
if RunService:IsStudio() then return end
local Players = game:GetService("Players")
for _,player in pairs(Players:GetPlayers()) do
SaveData(player)
print("Saved data for "..player.Name.." on shutdown.")
end
end)
5 comments
yes, use a table.
i normally only save on player leaving
can I have some type of an example on how to do this?
Send less requests
you'd never want to limit the datastore rate, you'd always want to request less.