local Players = game:GetService(“Players”)
local DataStoreService = game:GetService(“DataStoreService”)
local Saver = DataStoreService:GetDataStore(“SaveLeaderstats”)
Players.PlayerAdded:Connect(function(player)
local Data = nil
local success, errormessage = pcall(function()
Data = Saver:GetAsync(tostring(player.UserId))
end)
if success then
if Data then
for i, v in pairs(Data) do
player:WaitForChild(“SpellsOwned”):GetChildren().Value = v
end
end
else
error(errormessage)
end
end)
local function Save(player)
local SavedData = {}
for _, v in pairs(player.SpellsOwned:GetChildren()) do
SavedData[v.Name] = v.Value
end
local success, errormessage = pcall(function()
Saver:SetAsync(tostring(player.UserId), SavedData)
end)
if not success then
error(errormessage)
end
end
Players.PlayerRemoving:Connect(Save)
game:BindToClose(function()
for _, v in pairs(Players:GetPlayers()) do
Save(v)
end
end)
Try adding a delay using a wait() function when looping through each of the spells as this will prevent too many requests being sent and add a delay when the game is closing as it may shut down before all of the data is saves.
Here is an example:
game:BindToClose(function()
wait(5)
end)
Try not to set the number too high as there is a limit where the server will shut down without continuing to wait; however I am unsure what it is.
Additionally, you could try reducing the amount of SetAsync() functions by storing the data in a table as a json string using http service. You may find this link useful: HttpService:JSONEncode() Documention
You will also have to use :JSONDecode() when getting the data using :GetAsync() to convert it back into a table.