Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How do I make a DataStored Leaderboard?

I have been trying to get my leaderboard to save across sessions using datastores but I can't get it working. I have used many different examples but none have helped. I am trying to create a point system that gets 10 points added every 2 minutes. If somebody could fix my code or just point me in the right direction, I would really appreciate it.

Here is the code I ended up with:

local DataStore = game:GetService("DataStoreService")
local coinsDataStore = DataStore:GetDataStore("Coins")

local Players = game:GetService("Players")

game.Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder", player)
leaderstats.Name = "leaderstats"
local coin = Instance.new("IntValue", leaderstats)
coin.Name = "Coins"
	local key = player.UserId
	
	local data
	local s, e = pcall(function()
		data = coinsDataStore:GetAsync(key)
	end)
	if s then
		coin.Value = data	
	else
		coin.Value = 0
	end
	
	while true do
		wait(120)
		coin.Value = coin.Value + 10
	end
	
	coin.Value.Changed:Connect(function()
		local s, e = pcall(function()
		coinsDataStore:SetAsync(key, player.leaderstats["Coins"].Value)		
	end)
	if s then
		print("Success")		
	else	
		warn(e)
	end
	end)
end)

1 comment

0

move the loop down below the changed event

1 answer

Just move your loop down and it should work. Also, you didn't use the changed event properly.

local DataStore = game:GetService("DataStoreService")
local coinsDataStore = DataStore:GetDataStore("Coins")

local Players = game:GetService("Players")

game.Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder", player)
	leaderstats.Name = "leaderstats"
	local coin = Instance.new("IntValue", leaderstats)
	coin.Name = "Coins"
	local key = player.UserId

	local data
	local s, e = pcall(function()
		data = coinsDataStore:GetAsync(key)
	end)
	if s then
		coin.Value = data   
	else
		coin.Value = 0
	end


	coin.Changed:Connect(function()
		local s, e = pcall(function()
			coinsDataStore:SetAsync(key, player.leaderstats["Coins"].Value)     
		end)
		
		if s then
			print("Success")        
		else    
			warn(e)
		end
	end)
	
	while true do
		wait(10)
		coin.Value = coin.Value + 10
	end
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.