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

Leaderboard stats aren't saving?

scoreKey = "PlayerScore"
game.Players.PlayerAdded:connect(function(player)
local stat = Instance.new("IntValue")
stat.Name = "leaderstats"
stat.Parent = player
local WinTokens = Instance.new("IntValue")
WinTokens.Name = "WinTokens"
WinTokens.Parent = stat
WinTokens.Value = player:LoadNumber(scoreKey)
end)
 
game.Players.PlayerRemoving:connect(function(player)
    if player:FindFirstChild("leaderstats") then
        player:SaveNumber(scoreKey, player.leaderstats.WinTokens.Value)    
    end
end)



This script is a normal script in serverscriptservice.

I read the wiki on data persistence and made this script, but it doesn't work. Whats the problem?

2 answers

✓ Accepted answer
PlayerDataStore = game:GetService("DataStoreService"):GetDataStore("PlayerScore")

game.Players.PlayerAdded:Connect(function(player)
	local stats = Instance.new("Folder")
	stats.Name = "leaderstats"
	stats.Parent = player
	WinTokens = Instance.new("IntValue")
	WinTokens.Name = "WinTokens"
	WinTokens.Parent = stats
	WinTokens.Value = PlayerDataStore:GetAsync(player.UserId)

	player.leaderstats.WinTokens.Changed:Connect(function()
		PlayerDataStore:SetAsync(player.UserId, WinTokens.Value)
	end)
end)

game.Players.PlayerRemoving:connect(function(player)
    if player:FindFirstChild("leaderstats") then
         PlayerDataStore:SetAsync(player.UserId, WinTokens.Value)
    end
end)

If you've looked at the wiki and are having troubles putting it together, here's what it should be. When you use GetAsync(player.UserId) it returns a value attached with the player's id. That value is changed when you use SetAsync(player.UserId, WinTokens.Value) where WinTokens.Value is the value attached. I put an extra changed event in there so it always saves one the value changes. Hope this helps!

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