Datastore saving leaderstats

Hello, I’ve been making a roblox game and SOMETIMES the leaderstats data does not save. I’d say 9 out of 10 times i rejoin it saves, and the other doesnt. It’s really annoying and i haven’t found a fix for it yet. this is my script:

local DataStoreService = game:GetService("DataStoreService")
local playerDataStore = DataStoreService:GetDataStore("PlayerData")

local RANK_THRESHOLDS = {
	{rank = "Neutral", threshold = 0},
	{rank = "Collector", threshold = 1},
	{rank = "Spender", threshold = 100},
	{rank = "Big Spender", threshold = 500},
	{rank = "[💸]Platinum Spender", threshold = 1000},
	{rank = "[🏆] Master Spender", threshold = 5000},
	{rank = "[👑] Replica God", threshold = 10000},
}

-- Function to get rank based on Robux spent
local function getRank(robuxSpent)
	for i = #RANK_THRESHOLDS, 1, -1 do
		local data = RANK_THRESHOLDS[i]
		if robuxSpent >= data.threshold then
			return data.rank
		end
	end
	return "Default Rank"
end

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

	local purchaseCount = Instance.new("IntValue")
	purchaseCount.Name = "Purchases"
	purchaseCount.Value = 0
	purchaseCount.Parent = leaderstats

	local robuxSpent = Instance.new("IntValue")
	robuxSpent.Name = "Spent"
	robuxSpent.Value = 0
	robuxSpent.Parent = leaderstats

	-- Create a separate folder for hidden stats
	local hiddenStats = Instance.new("Folder")
	hiddenStats.Name = "HiddenStats"
	hiddenStats.Parent = player

	local rank = Instance.new("StringValue")
	rank.Name = "Rank"
	rank.Parent = hiddenStats

	-- Load data from DataStore
	local success, data = pcall(function()
		return playerDataStore:GetAsync(player.UserId)
	end)

	if success and data then
		if data.purchaseCount then
			purchaseCount.Value = data.purchaseCount
		end
		if data.robuxSpent then
			robuxSpent.Value = data.robuxSpent
		end
	end

	-- Set initial rank
	rank.Value = getRank(robuxSpent.Value)

	-- Save data when the game is closing
	game:GetService("Players").PlayerRemoving:Connect(function()
		local success, error = pcall(function()
			playerDataStore:UpdateAsync(player.UserId, {
				purchaseCount = purchaseCount.Value,
				robuxSpent = robuxSpent.Value
			})
		end)

		if not success then
			warn("Failed to save data for player " .. player.Name .. ": " .. error)
		end
	end)
end)

game:GetService("Players").PlayerRemoving:Connect(function(player)
	local leaderstats = player:FindFirstChild("leaderstats")
	local purchaseCount = leaderstats and leaderstats:FindFirstChild("Purchases")
	local robuxSpent = leaderstats and leaderstats:FindFirstChild("Spent")

	if purchaseCount and robuxSpent then
		-- Save data to DataStore
		local success, error = pcall(function()
			playerDataStore:UpdateAsync(player.UserId, function(oldData)
				oldData = oldData or {}  -- In case there is no existing data for the player
				oldData.purchaseCount = purchaseCount.Value
				oldData.robuxSpent = robuxSpent.Value
				return oldData
			end)
		end)

		if not success then
			warn("Failed to save data for player " .. player.Name .. ": " .. error)
		end
	end
end)

game:GetService("MarketplaceService").PromptPurchaseFinished:Connect(function(player, assetId, isPurchased)
	if isPurchased then
		print(player.Name .. " bought an item with AssetID: " .. assetId)
		local leaderstats = player:FindFirstChild("leaderstats")
		local hiddenStats = player:FindFirstChild("HiddenStats")
		local purchaseStat = leaderstats and leaderstats:FindFirstChild("Purchases")
		local robuxSpentStat = leaderstats and leaderstats:FindFirstChild("Spent")
		local rankStat = hiddenStats and hiddenStats:FindFirstChild("Rank")

		if purchaseStat then
			purchaseStat.Value = purchaseStat.Value + 1
		end

		if robuxSpentStat then
			local productInfo = game.MarketplaceService:GetProductInfo(assetId)
			if productInfo then
				local price = productInfo.PriceInRobux
				robuxSpentStat.Value = robuxSpentStat.Value + price
				if rankStat then
					rankStat.Value = getRank(robuxSpentStat.Value)
				end
			end
		end
	else
		return
	end
end)

-- Save data for all players when the game is closing
game:BindToClose(function()
	for _, player in pairs(game.Players:GetPlayers()) do
		player:Kick("Server is shutting down. Your data is being saved.")
	end
end)

You’re making a .PlayerRemoving connection every time .PlayerAdded is run. Not only is this bad because you should only be doing this once, but you’re also not checking if the player that left is the right player to save data too, meaning the wrong data is being saved to the wrong person. Instead, keep them entirely separate. I’m not sure why you do this inside .PlayerAdded and outside, only have it once.

I tried to make the following changes, could you please tell me if this looks better?

local DataStoreService = game:GetService("DataStoreService")
local playerDataStore = DataStoreService:GetDataStore("PlayerData")

local RANK_THRESHOLDS = {
	{rank = "Neutral", threshold = 0},
	{rank = "Collector", threshold = 1},
	{rank = "Spender", threshold = 100},
	{rank = "Big Spender", threshold = 500},
	{rank = "[💸]Platinum Spender", threshold = 1000},
	{rank = "[🏆] Master Spender", threshold = 5000},
	{rank = "[👑] Replica God", threshold = 10000},
}

-- Function to get rank based on Robux spent
local function getRank(robuxSpent)
	for i = #RANK_THRESHOLDS, 1, -1 do
		local data = RANK_THRESHOLDS[i]
		if robuxSpent >= data.threshold then
			return data.rank
		end
	end
	return "Default Rank"
end

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

	local purchaseCount = Instance.new("IntValue")
	purchaseCount.Name = "Purchases"
	purchaseCount.Value = 0
	purchaseCount.Parent = leaderstats

	local robuxSpent = Instance.new("IntValue")
	robuxSpent.Name = "Spent"
	robuxSpent.Value = 0
	robuxSpent.Parent = leaderstats

	-- Create a separate folder for hidden stats
	local hiddenStats = Instance.new("Folder")
	hiddenStats.Name = "HiddenStats"
	hiddenStats.Parent = player

	local rank = Instance.new("StringValue")
	rank.Name = "Rank"
	rank.Parent = hiddenStats

	-- Load data from DataStore
	local success, data = pcall(function()
		return playerDataStore:GetAsync(player.UserId)
	end)

	if success and data then
		if data.purchaseCount then
			purchaseCount.Value = data.purchaseCount
		end
		if data.robuxSpent then
			robuxSpent.Value = data.robuxSpent
		end
	end

	-- Set initial rank
	rank.Value = getRank(robuxSpent.Value)

	-- Save data when the player is leaving
	player.Changed:Connect(function(property)
		if property == "Parent" and player.Parent == nil then
			local success, error = pcall(function()
				playerDataStore:UpdateAsync(player.UserId, {
					purchaseCount = purchaseCount.Value,
					robuxSpent = robuxSpent.Value
				})
			end)

			if not success then
				warn("Failed to save data for player " .. player.Name .. ": " .. error)
			end
		end
	end)
end)

game:GetService("MarketplaceService").PromptPurchaseFinished:Connect(function(player, assetId, isPurchased)
	if isPurchased then
		print(player.Name .. " bought an item with AssetID: " .. assetId)
		local leaderstats = player:FindFirstChild("leaderstats")
		local hiddenStats = player:FindFirstChild("HiddenStats")
		local purchaseStat = leaderstats and leaderstats:FindFirstChild("Purchases")
		local robuxSpentStat = leaderstats and leaderstats:FindFirstChild("Spent")
		local rankStat = hiddenStats and hiddenStats:FindFirstChild("Rank")

		if purchaseStat then
			purchaseStat.Value = purchaseStat.Value + 1
		end

		if robuxSpentStat then
			local productInfo = game.MarketplaceService:GetProductInfo(assetId)
			if productInfo then
				local price = productInfo.PriceInRobux
				robuxSpentStat.Value = robuxSpentStat.Value + price
				if rankStat then
					rankStat.Value = getRank(robuxSpentStat.Value)
				end
			end
		end
	else
		return
	end
end)

-- Save data for all players when the game is closing
game:BindToClose(function()
	for _, player in pairs(game.Players:GetPlayers()) do
		player:Kick("Server is shutting down. Your data is being saved.")
	end
end)

This updated script efficiently manages player data by securely saving it when they leave the game, enhancing reliability. Overall, your script looks good!

player.Changed is really weird and it seems like .AncestryChanged would do the same thing. Since all you’re doing is trying to detect if the player left then you should just be using .PlayerRemoving.

Additionally, your script has a major flaw in it. You don’t seem to care if the :GetAsync method fails, and instead you will default the player’s stats to 0. Now if the player leaves the game (presumably because their stats failed to load) and then the UpdateAsync request succeeds, they’ve just overwritten their data.

This fixes my aforementioned issue with saving to the wrong player, but using .Changed is weird. You don’t need to be checking if they left like that.

Create a .PlayerRemoving connection outside of the .PlayerAdded connection. Redefine any variables you need to save, save, and done.

I have made some changes, I’m pretty sure this script works as intended now. I’ve created the .PlayerRemoving outside of the .PlayerAdded and made a few tweaks, please lmk if that looks right:

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

	local purchaseCount = Instance.new("IntValue")
	purchaseCount.Name = "Purchases"
	purchaseCount.Value = 0
	purchaseCount.Parent = leaderstats

	local robuxSpent = Instance.new("IntValue")
	robuxSpent.Name = "Spent"
	robuxSpent.Value = 0
	robuxSpent.Parent = leaderstats

	local hiddenStats = Instance.new("Folder")
	hiddenStats.Name = "HiddenStats"
	hiddenStats.Parent = player

	local rank = Instance.new("StringValue")
	rank.Name = "Rank"
	rank.Parent = hiddenStats

	local success, data = pcall(function()
		return playerDataStore:GetAsync(player.UserId)
	end)

	if success and data then
		if data.purchaseCount then
			purchaseCount.Value = data.purchaseCount
		end
		if data.robuxSpent then
			robuxSpent.Value = data.robuxSpent
		end
	end

	rank.Value = getRank(robuxSpent.Value)

	player.CharacterAdded:Connect(function(character)
		character:WaitForChild("Humanoid").Died:Connect(function()
			if player.Parent == game.Players then
				playerDataStore:UpdateAsync(player.UserId, function(oldData)
					oldData = oldData or {}
					oldData.purchaseCount = purchaseCount.Value
					oldData.robuxSpent = robuxSpent.Value
					return oldData
				end)
			end
		end)
	end)
end)

game.Players.PlayerRemoving:Connect(function(player)
	local success, error = pcall(function()
		playerDataStore:UpdateAsync(player.UserId, function(oldData)
			oldData = oldData or {}
			local leaderstats = player:FindFirstChild("leaderstats")
			local hiddenStats = player:FindFirstChild("HiddenStats")
			local purchaseStat = leaderstats and leaderstats:FindFirstChild("Purchases")
			local robuxSpentStat = leaderstats and leaderstats:FindFirstChild("Spent")
			oldData.purchaseCount = purchaseStat and purchaseStat.Value or 0
			oldData.robuxSpent = robuxSpentStat and robuxSpentStat.Value or 0
			return oldData
		end)
	end)

	if not success then
		warn("Failed to save data for player " .. player.Name .. ": " .. error)
	end
end)

game:GetService("MarketplaceService").PromptPurchaseFinished:Connect(function(player, assetId, isPurchased)
	if isPurchased then
		local leaderstats = player:FindFirstChild("leaderstats")
		local hiddenStats = player:FindFirstChild("HiddenStats")
		local purchaseStat = leaderstats and leaderstats:FindFirstChild("Purchases")
		local robuxSpentStat = leaderstats and leaderstats:FindFirstChild("Spent")
		local rankStat = hiddenStats and hiddenStats:FindFirstChild("Rank")

		if purchaseStat and robuxSpentStat then
			purchaseStat.Value = purchaseStat.Value + 1
			local productInfo = game.MarketplaceService:GetProductInfo(assetId)
			if productInfo then
				local price = productInfo.PriceInRobux
				robuxSpentStat.Value = robuxSpentStat.Value + price
				if rankStat then
					rankStat.Value = getRank(robuxSpentStat.Value)
				end
			end
		end
	end
end)

game:BindToClose(function()
	for _, player in ipairs(game.Players:GetPlayers()) do
		player:Kick("Server is shutting down. Your data is being saved.")
	end
end)