Leaderstats script not working

I have a leaderstats and datastore script with multiple stats and there are two problems:

  1. The queue fills up everytime I leave and
  2. Both of the stats get set to the same number

Script:

local dataStore = game:GetService("DataStoreService")
local statSave = dataStore:GetDataStore("LeaderStatSave")

game.Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder", player)
	leaderstats.Name = "leaderstats"
	
	local totalWins = Instance.new("IntValue", leaderstats)
	totalWins.Name = "Wins"
	totalWins.Value = statSave:GetAsync(player.UserId, player.leaderstats.Wins.Value) or 0
	print(player.Name .. "'s Total Wins were loaded.")
	
	local totalAttempts = Instance.new("IntValue", leaderstats)
	totalAttempts.Name = "Attempts"
	totalAttempts.Value = statSave:GetAsync(player.UserId, player.leaderstats.Attempts.Value) or 0
	print(player.Name .. "'s Total Attempts were loaded.")
end)

game.Players.PlayerRemoving:Connect(function(player)
	statSave:SetAsync(player.UserId, player.leaderstats.Wins.Value)
	statSave:SetAsync(player.UserId, player.leaderstats.Attempts.Value)
end)

I’ve made some changes to your script that should fix these issues.

  1. To prevent the queue from filling up, we’ll use :UpdateAsync() instead of :SetAsync(). This will allow us to properly handle cases when multiple instances of the game are trying to save data at the same time.
  2. The issue with the stats getting set to the same number seems to be due to the misuse of :GetAsync(). You should pass only the key (in this case, the player.UserId concatenated with the stat name) to retrieve the value for each stat.

Here’s the updated script:

local dataStore = game:GetService("DataStoreService")
local statSave = dataStore:GetDataStore("LeaderStatSave")

game.Players.PlayerAdded:Connect(function(player)
    local leaderstats = Instance.new("Folder", player)
    leaderstats.Name = "leaderstats"

    local totalWins = Instance.new("IntValue", leaderstats)
    totalWins.Name = "Wins"
    totalWins.Value = statSave:GetAsync(player.UserId .. "_Wins") or 0
    print(player.Name .. "'s Total Wins were loaded.")

    local totalAttempts = Instance.new("IntValue", leaderstats)
    totalAttempts.Name = "Attempts"
    totalAttempts.Value = statSave:GetAsync(player.UserId .. "_Attempts") or 0
    print(player.Name .. "'s Total Attempts were loaded.")
end)

game.Players.PlayerRemoving:Connect(function(player)
    statSave:UpdateAsync(player.UserId .. "_Wins", function(oldValue)
        return player.leaderstats.Wins.Value
    end)

    statSave:UpdateAsync(player.UserId .. "_Attempts", function(oldValue)
        return player.leaderstats.Attempts.Value
    end)
end)

Now, the script should properly load and save the values for each stat and avoid the queue filling up.

Also, you can try using DataStore2 to avoid this type of issues: How to use DataStore2 - Data Store caching and data loss prevention