This is an interesting predicament. I’ve built a system that collects and stores the number of letters that a player has touched and when they leave the game, these values are saved to the DataStore. The DataStore works beautifully… for one letter. The rest, it just seems to completely skip over. Let me explain:
local DataStoreService = game:GetService("DataStoreService")
local playerData = DataStoreService:GetDataStore("PlayerData")
local RunService = game:GetService("RunService")
local function onPlayerJoin(Player)
local leaderstats = Instance.new("Folder") --It's essential that the folder is called "leaderstats".
leaderstats.Name = "leaderstats"
leaderstats.Parent = Player
local a = Instance.new("IntValue")
a.Name = "a"
a.Parent = leaderstats
local b = Instance.new("IntValue")
b.Name = "b"
b.Parent = leaderstats
local c = Instance.new("IntValue")
c.Name = "c"
c.Parent = leaderstats
local d = Instance.new("IntValue")
d.Name = "d"
d.Parent = leaderstats
local PlayerUserId = "Player_" .. Player.UserId
local data = playerData:GetAsync(PlayerUserId)
if data then
a.Value = data["a"]
b.Value = data["b"]
c.Value = data["c"]
d.Value = data["d"]
else
a.Value = 0
b.Value = 0
c.Value = 0
d.Value = 0
end
end
local function create_table(Player)
local player_stats = {}
for _, stat in pairs (Player.leaderstats:GetChildren()) do
player_stats[stat.Name] = stat.Value
end
return player_stats
end
local function saveData(Player)
local player_stats = create_table(Player)
local PlayerUserId = "Player_" .. Player.UserId
local tries = 0
local success
repeat
tries = tries + 1
success = pcall(function()
playerData:GetAsync(PlayerUserId, player_stats)
end)
if not success then wait(1) end
until tries == 3 or success
if not success then
warn("Could not save data.")
end
end
game.Players.PlayerAdded:Connect(onPlayerJoin)
game.Players.PlayerRemoving:Connect(saveData)
game:BindToClose(function()
for i , v in pairs (game.Players:GetPlayers()) do
saveData(v)
end
end)
When I’ve collected letters, both in the studio and on Roblox itself (and yes, I have API services enabled), the leaderboard updates and functions as it should. But when I leave the game and return, it seems that the a’s store just fine, but that’s it. Everything else is back to 0. When I use print(player_stats) in the saveData() function, it prints a table of all the letters I’ve collected in-game perfectly fine. Somehow, for some reason, only the first of those four values are actually being uploaded to the DataStore.
Others have said that the game may be quitting before the DataStore has been written into, which is why I’ve implemented the BindToClose function at the bottom of the script. But that didn’t do anything, it seems. What could I be doing wrong? I must have messed up the syntax somewhere, or maybe I don’t fully understand how DataStore tables work.
P.S. I’ve changed the variables for privacy purposes, but that shouldn’t affect the script you see here online.