One of the values on my leaderstats does not save

local datastores = game:GetService("DataStoreService")
local datastore = datastores:GetDataStore("DataStore")
local players = game:GetService("Players")

local function deserializeData(player, data)
	local leaderstats = player.leaderstats
	for statName, statValue in next, data do
		local stat = leaderstats:FindFirstChild(statName)
		if statName then
			stat.Value = statValue
		end
	end
end

local function serializeData(player)
	local data = {}
	local leaderstats = player.leaderstats
	for _, stat in ipairs(leaderstats:GetChildren()) do
		data[stat.Name] = stat.Value
	end
	return data
end

local function onPlayerAdded(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player

	local knockouts = Instance.new("IntValue")
	knockouts.Name = "CREDITS"
	knockouts.Parent = leaderstats

	local wipeouts = Instance.new("IntValue")
	wipeouts.Name = "XP"
	wipeouts.Parent = leaderstats
	
	local bs = Instance.new("IntValue")
	bs.Name = "BANK"
	bs.Parent = leaderstats
	
	while true do task.wait(300)
		wipeouts.Value += 5
	end

	local success, result = pcall(function()
		return datastore:GetAsync("Stats_"..player.UserId)
	end)

	if success then
		if result then
			deserializeData(player, result)
		end
	else
		warn(result)
	end
end

local function onPlayerRemoving(player)
	local data = serializeData(player)

	local success, result = pcall(function()
		return datastore:SetAsync("Stats_"..player.UserId, data)
	end)

	if success then
		if result then
			print(result)
		end
	else
		warn(result)
	end
end

local function onServerShutdown()
	for _, player in ipairs(players:GetPlayers()) do
		local data = serializeData(player)

		local success, result = pcall(function()
			return datastore:SetAsync("Stats_"..player.UserId, data)
		end)

		if success then
			if result then
				print(result)
			end
		else
			warn(result)
		end
	end
end

players.PlayerAdded:Connect(onPlayerAdded)
players.PlayerRemoving:Connect(onPlayerRemoving)
game:BindToClose(onServerShutdown)

Hi all, this is a script I have for the leaderstats to save, the local knockouts saves, but the local wipeouts doesnt. Is there anything seemingly wrong with the script?

1 Like

Your problem is that inside the onPlayerAdded function, you have an infinite loop:

while true do
	task.wait(300)
	wipeouts.Value += 5
end

Because of this, the loop blocks the rest of the code from running, so the DataStore loading part never gets executed — that’s why XP isn’t being saved.

The fix is simple: you need to run this loop in a separate thread so it doesn’t block the rest of your logic. Replace it with:

task.spawn(function()
	while player and player.Parent do
		task.wait(300)
		wipeouts.Value += 5
	end
end)
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.