Best Way to Get Leaderstats

Screenshot 2024-01-22 at 4.41.27 PM

How it works

DataStore (script) clones the leaderstats (folder) to to the player when the player is added, plus the data store part.

Just adding a type of variable to leaderstats (folder).

Easy to use and easy to change.

Would it be better to use this method to get leaderstats to the player or just keep it as a script (change the variable inside the script).

2 Likes

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.

1 Like

kinda like this

local stats = {
	{"Coins", 0},
	{"Money", 0},
	{"Wins", 0}
}
3 Likes

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.

1 Like