I have a datastore script, But i don’t know if there will be data loss. can someone help me find out, or just tell me how to make it better in general?
any help is greatly appreciated, Thanks!
local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetDataStore("DataStore")
local function SaveData(player)
local ItemsToSave = {}
local s,e = pcall(function()
for i,Stat in player.leaderstats:GetChildren() do
table.insert(ItemsToSave,{Stat.Name,Stat.Value})
print(ItemsToSave)
end
DataStore:SetAsync(player.UserId,ItemsToSave)
end)
if s then
print("Player data Saved ✅")
end
if e then
warn("Player data not Saved ⚠️")
end
end
local function LoadData(Player)
local data
local s,e = pcall(function()
data = DataStore:GetAsync(Player.UserId)
if data then
for i,v in data do
local StatName = v[1]
local StatValue = v[2]
Player.leaderstats:FindFirstChild(StatName).Value = StatValue
end
end
end)
if s then
print("Player data loaded ✅")
end
if e then
warn("Player data not loaded ⚠️")
end
end
local function CreateLeaderstats(Player)
local success,errormessage = pcall(function()
if not Player:FindFirstChild("leaderstats") then
local leaderstats = script.leaderstats:Clone()
leaderstats.Parent = Player
end
end)
if success then
print("leaderstats created ✅")
end
if errormessage then
warn("Leaderstats could not be created ⚠️")
end
end
game.Players.PlayerAdded:Connect(function(plr)
CreateLeaderstats(plr)
LoadData(plr)
end)
game:BindToClose(function()
for _,Player in game.Players:GetPlayers() do
SaveData(Player)
end
end)
game.Players.PlayerRemoving:Connect(function(player)
SaveData(player)
end)