I just wonder that is this code going to have some data saving problem sometime?
Is it a good way to save all of the values in the leaderstats folder?
local Players = game:GetService('Players')
local DataStoreService = game:GetService('DataStoreService')
local StoreKey = DataStoreService:GetDataStore('DataKeyTest')
Players.PlayerAdded:Connect(function(player: Player)
local leaderstatsFolder = script:WaitForChild('leaderstats')
leaderstatsFolder.Parent = player
local data
local succ, err = pcall(function()
data = StoreKey:GetAsync('player_'..player.UserId)
end)
print(data)
if succ == true then
print('Data is fully loaded.')
if data ~= nil then
print('Data is not nil, setting data...')
for dataVal = #data - (#data - 1), #data, 1 do
leaderstatsFolder:GetChildren()[dataVal].Value = data[dataVal]
end
print('Successfully set all data!!')
elseif data == nil then
print('Data is nil, cannot set data if it nil.')
end
elseif succ == false then
warn('Failed to load data: '..tostring(err))
end
end)
Players.PlayerRemoving:Connect(function(player: Player)
local data = {}
for _, valuesInFolder in pairs(player:WaitForChild('leaderstats'):GetChildren()) do
if valuesInFolder:IsA('ValueBase') then
table.insert(data, valuesInFolder.Value)
end
end
local succ, err = pcall(function()
data = StoreKey:SetAsync('player_'..player.UserId, data)
end)
if succ == true then
print('Successfully saved player datas!!')
elseif succ == false then
warn('Failed to save player datas: '..tostring(err))
end
end)