I alredy confirm that the error doesn’t come from the bind to close so i have no idea how to fix this
local players = game:GetService("Players")
local dataStoreService = game:GetService("DataStoreService")
local dataStore = dataStoreService:GetDataStore("MyDataStoreKey")
local RunService = game:GetService("RunService")
local playerData = script.PlayerData
local function SaveData(player)
local data = {}
for _, folder in pairs(player:GetChildren()) do
if playerData:FindFirstChild(folder.Name) then
if playerData[folder.Name]:GetAttribute("SaveChildren") == true then
data[folder.Name] = {}
if playerData[folder.Name]:GetAttribute("SaveChildrenValues") == true then
for _, child in pairs(folder:GetChildren()) do
if not child:GetAttribute("DoNotSaveValue") then
table.insert(data[folder.Name], {child.Name, child.Value, child.ClassName})
end
end
else
for _, child in pairs(folder:GetChildren()) do
if not child:GetAttribute("DoNotSaveValue") then
table.insert(data[folder.Name], {child.Name, child.ClassName})
end
end
end
end
end
end
local success, errorMsg = pcall(function()
dataStore:SetAsync(player.UserId.."Key", data)
end)
if success then
print("Saved Data")
else
warn(errorMsg)
end
end
local function LoadData(player)
for _, v in pairs(playerData:GetChildren()) do
v:Clone().Parent = player
end
local data
local success, errorMsg = pcall(function()
data = dataStore:GetAsync(player.UserId.."Key")
end)
if errorMsg then
warn(errorMsg)
player:Kick("Could not load Data")
end
if data then
for i, v in pairs(data) do
if #v > 0 then
for x, c in pairs(v) do
if player[tostring(i)]:FindFirstChild(c[1]) then
player[tostring(i)]:FindFirstChild(c[1]).Value = c[2]
else
local value
if c[3] == nil then
value = Instance.new(tostring(c[2]))
else
value = Instance.new(tostring(c[3]))
end
value.Name = c[1]
value.Value = c[2]
value.Parent = player[tostring(i)]
end
end
end
end
end
end
local function PlayerRemoving(player)
SaveData(player)
end
players.PlayerAdded:Connect(LoadData)
players.PlayerRemoving:Connect(PlayerRemoving)
game:BindToClose(function()
for _, player in pairs(players:GetPlayers()) do
SaveData(player)
end
end)