im making a game right now and i have realized that players with large amounts of cash,
17Qa+ experience alot of dataloss and lag, how can i store my data better??
im currently using this script:
local dataStoreService = game:GetService("DataStoreService")
local leaderstatsDataStore = dataStoreService:GetGlobalDataStore("PlayerStats")
local loaded = {}
game.Players.PlayerAdded:connect(function(player)
local leaderstats = player:WaitForChild("leaderstats")
if player.UserId > 0 and player.Parent then
local leaderstatsData = leaderstatsDataStore:GetAsync(player.UserId)
if leaderstatsData ~= "Request rejected" then
if leaderstatsData then
for i, stat in ipairs(leaderstats:GetChildren()) do
local value = leaderstatsData[stat.Name]
if value then
stat.Value = value
end
end
end
loaded[player] = true
end
end
end)
game.Players.PlayerRemoving:connect(function(player)
local leaderstats = player:FindFirstChild("leaderstats")
if leaderstats then
if loaded[player] then
local leaderstatsData = {}
for i, stat in ipairs(leaderstats:GetChildren()) do
leaderstatsData[stat.Name] = stat.Value
end
leaderstatsDataStore:SetAsync(player.UserId, leaderstatsData)
end
end
loaded[player] = nil
end)
If your DataStore is otherwise working correctly then I recommend watching this YouTube tutorial by 5uphi that should help explain to you how to compress the data before storing it into your DataStore: Compress / Optimize Datastore - Roblox Scripting Tutorial
You asked what pcall does. I gave you a basic example.
Basically, instead of doing Asyncs by themselves, wrap them in a pcall
function setAsync(ds:DataStore, key:any, value:any)
local success, err = pcall(function()
ds:SetAsync(key, value)
end)
if not success then
warn(err)
wait(1)
setAsync(ds, key, value)
end
end
And then instead of leaderstatsDataStore:SetAsync(player.UserId, leaderstatsData) do setAsync(leaderstatsDataStore, player.UserId, leaderstatsData)
Same goes for getting async.
Edit: Added a delay so that you won’t get rate limited
game.Players.PlayerRemoving:connect(function(player)
local leaderstats = player:FindFirstChild("leaderstats")
if leaderstats then
if loaded[player] then
local leaderstatsData = {}
for i, stat in ipairs(leaderstats:GetChildren()) do
leaderstatsData[stat.Name] = stat.Value
end
task.spawn(function()
setAsync(leaderstatsDataStore, player.UserId, leaderstatsData)
end)
end
end
loaded[player] = nil
end)