I think I made away to create a stat based of the a dictionary’s key and value
local values = {
Class = "value"; -- Name_of_Stat = Default_Stat
Other_thing = 34534;
-- etc, etc
}
for name, value in pairs(values) do
local text = typeof(value).."Value"
local new = Instance.new(string.upper(string.sub(text, 0, 1)) .. string.sub(text, 2)) -- Should, in theory create a value instance based of the value in the dictionary
new.Name = name
new.Value = value
new.Parent = leaderstatsFolder
end
I think it doesn’t take a lot extra effort to get creative with these kinds of things
Edit:
And here’s a screenshot to show that this worked for me.
function makeStat(name, valueType, value, leaderstats: Folder)
--[[
Name: name of leaderstats value that will show up on the leaderboard
ValueType: ValueBase
Value: Value Type that will go in that value object
leaderstats: Your leaderstats folder
]]
local stat = Instance.new(valueType, leaderstats)
stat.Name = name
stat.Value = value
return stat
end
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder", player)
leaderstats.Name = "leaderstats"
local money = makeStat("Coins", "IntValue", 0, leaderstats)
end)
My preferred way is to just “build” the leaderstats Folder in Studio and :Clone it when a Player joins:
local leaderstatsPrefab = script.leaderstats
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = leaderstatsPrefab:Clone()
leaderstats.Parent = player
end)
If you want a handy dictionary to access the ValueObjects:
local playerStats = {}
local leaderstatsPrefab = script.leaderstats
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = leaderstatsPrefab:Clone()
playerStats[player] = leaderstats
for _, valueObject in leaderstats:GetChildren() do
assert(valueObject:IsA("ValueBase"))
playerStats[player][valueObject.Name] = valueObject
end
leaderstats.Parent = player
end)
Or even handy-er, wrappers over the ValueObjects so you don’t have to type .Value constantly:
local leaderstatsPrefab = script.leaderstats
local playerLeaderStats = setmetatable({}, {__mode = "kv"})
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = leaderstatsPrefab:Clone()
playerLeaderStats[player] = setmetatable({}, {
__index = function(self, key)
local valueObject = leaderstats:FindFirstChild(key)
assert(valueObject ~= nil and valueObject:IsA("ValueBase"))
return valueObject.Value
end,
__newindex = function(self, key, value)
local valueObject = leaderstats:FindFirstChild(key)
assert(valueObject ~= nil and valueObject:IsA("ValueBase"))
valueObject.Value = value
end
})
leaderstats.Parent = player
--Tests. Also shows how you could use it.
local stats = playerLeaderStats[player]
print(stats.Luck)
stats.Luck += 5
print(stats.Luck)
print(stats.AAAAAAA) --Should error
stats.Luck = nil --Should error, wrong type
end)