We use cookies on this site to enhance your user experience

Data Store to Leaderboard

Data Store to Leaderboard

Sep 05 2018, 6:49 PM PST

This code sample retrieves a player’s saved gold from a data store and puts the returned value onto the leaderboard. Note that this sample does not save players’ gold — it only loads it.

local Players = game:GetService("Players")
local goldDataStore = game:GetService("DataStoreService"):GetDataStore("Gold") 

local STARTING_GOLD = 100

local function onPlayerAdded(player)
	local playerKey = "Player_" .. player.UserId

	local leaderstats = Instance.new("IntValue")
	leaderstats.Name = "leaderstats"

	local gold = Instance.new("IntValue", leaderstats)
	gold.Name = "Gold"

	local myGold
	local success, err = pcall(function()
		myGold = goldDataStore:GetAsync(playerKey)
	end)
	if success then
		gold.Value = myGold
	else
		gold.Value = STARTING_GOLD
	end

	leaderstats.Parent = player
end

for _, player in pairs(Players:GetPlayers()) do
	onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)