I prefer the method you show in that image as it allows for you to easily add more values, although you could manage values in a table in the server script.
Yeah. I also use a format like this as I find it easier to read in terms of additions of values:
Code
local Players = game.Players
local DSService = game:GetService("DataStoreService")
local PlrDataStore = DSService:GetDataStore("PlayerData")
--//
local StatsToAdd = {
[1] = {
Name = "Cash",
Type = "NumberValue",
Save = true,
DefaultValue = 500,
},
[2] = {
Name = "Server Gems",
Type = "NumberValue",
Save = false,
DefaultValue = 0,
},
}
--//
local function LoadPlayerData(player)
local playerKey = "Player_" .. player.UserId
local data
local success, err = pcall(function()
data = PlrDataStore:GetAsync(playerKey)
end)
if success then
return data
else
warn(err)
return nil
end
end
local function SavePlayerData(player, data)
local playerKey = "Player_" .. player.UserId
local success, err = pcall(function()
PlrDataStore:SetAsync(playerKey, data)
end)
if not success then
warn(err)
end
end
Players.PlayerAdded:Connect(function(player)
local folder = Instance.new("Folder", player)
folder.Name = "leaderstats"
local data = LoadPlayerData(player) or {}
for _, item in pairs(StatsToAdd) do
local newStat = Instance.new(item.Type, folder)
newStat.Name = item.Name
newStat.Value = data[item.Name] or item.DefaultValue
end
end)
Players.PlayerRemoving:Connect(function(player)
local data = {}
for _, item in pairs(StatsToAdd) do
if item.Save then
local stat = player:FindFirstChild("leaderstats"):FindFirstChild(item.Name)
if stat then
data[item.Name] = stat.Value
end
end
end
SavePlayerData(player, data)
end)
That’s probably really long considering I use data stores here, but you get the jist.