So I'm working on a DataStore system which loads the player's data when they join and save it when they leave or when the server shuts down. The problem is that when testing the game online, the data doesn't save. I'm not playing with anyone so I don't know if it's the game.OnClose function. I receive no errors in the console too. The code is below, if you could help it would mean a lot to me.
Please take note that this isn't the full script.
local datastore = game:GetService("DataStoreService")
-- When the Player Joins
game.Players.PlayerAdded:connect(function(Player)
Setup_Leaderstats(Player)
Setup_StoreStats(Player)
LoadData(Player, Player:FindFirstChild("leaderstats"))
end)
-- Functions
function Setup_StoreStats(Player)
local Skins = replicatedstorage.Resources:FindFirstChild("Skins")
-- Create Storage
local Storage = Instance.new("IntValue", Player)
Storage.Name = "Storage"
-- Selected Skin
local SelSkin = Instance.new("IntValue", Storage)
SelSkin.Name = "SelectedSkinTexture"
-- Create Skin Storage
local Skns = Instance.new("IntValue", Storage)
Skns.Name = "Skins"
for _,v in pairs(Skins:GetChildren()) do
if v:IsA("IntValue") then
local newvalue = Instance.new("BoolValue", Skns)
newvalue.Name = v.Name
end
end
-- Load Skins
wait(0.5)
LoadData(Player, Skns)
LoadData(Player, Storage)
end
function LoadData(player, data)
local Data = datastore:GetDataStore(player.Name.."Stats")
--
for _,v in pairs(data:GetChildren()) do
--
v.Value = Data:GetAsync(v.Name)
--
end
end
function PermanentSave(Player, data)
if Player then
local Data = datastore:GetDataStore(Player.Name.."Stats")
if data then
for _,i in pairs(data:GetChildren()) do
Data:SetAsync(i.Name, i.Value)
end
end
end
end
function SaveAllData(Player)
PermanentSave(Player, Player:FindFirstChild("Storage"))
PermanentSave(Player, Player:FindFirstChild("Storage").Skins)
PermanentSave(Player, Player:FindFirstChild("leaderstats"))
end
-- Player Removing and Game Close
game.Players.PlayerRemoving:connect(function(player)
if player then
SaveAllData(player)
end
end)
game.OnClose = function()
for i,v in pairs(game.Players:GetChildren()) do
SaveAllData(v)
end
end

1 comment
Try adding a wait after the for loop, the game might be closing before it saves data.