It works great but saves each item twice
local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetDataStore("AvatarDataStore")
local PlayersToSave = {}
local TimeBetweenAutoSave = 60
local Players = game:GetService("Players")
local RS = game:GetService("ReplicatedStorage")
local Extras = RS:WaitForChild("Extras")
local Message = Extras:WaitForChild("Message")
function SavePlayersData(player)
local Wearing = player:WaitForChild("Wearing")
local key = "Wearing_"..player.UserId
local itemTable = {}
for _, item in ipairs(Wearing:GetChildren()) do
itemTable[item.Name.."|"..item.ClassName] = item.Value
end
local success, errormessage = pcall(function()
DataStore:SetAsync(key, itemTable)
end)
if success then
else
print("Avatar save failed")
warn(errormessage)
local ErrorMessage = Message:Clone()
ErrorMessage.Parent = player.PlayerGui.PopUps
ErrorMessage.Message.Text = ("Your avatar failed to save. This will not cause you to lose any items. You may have to reapply them to your avatar though")
end
end
Players.PlayerAdded:Connect(function(player)
local key = "Wearing_"..player.UserId
local itemsEquipped
local success, errormessage = pcall(function()
itemsEquipped = DataStore:GetAsync(key)
end)
if success then
else
print("Avatar failed to load!")
warn(errormessage)
local ErrorMessage = Message:Clone()
ErrorMessage.Parent = player.PlayerGui.PopUps
ErrorMessage.Message.Text = ("Your avatar failed to load")
end
if type(itemsEquipped) == "table" then
for field, value in pairs(itemsEquipped) do
local name = string.split(field, "|")[1]
local class = string.split(field, "|")[2]
local instanceValue = Instance.new(class)
instanceValue.Parent = player.Wearing
instanceValue.Value = value
instanceValue.Name = name
end
end
end)
Players.PlayerRemoving:Connect(function(player)
SavePlayersData(player)
end)
while task.wait(TimeBetweenAutoSave) do
for _, player in ipairs(Players:GetPlayers()) do
SavePlayersData(player)
end
end
game:BindToClose(function()
if not game:GetService("RunService"):IsStudio() and #Players:GetPlayers() > 1 then
for _, player in ipairs(Players:GetPlayers()) do
SavePlayersData(player)
end
end
end)