Multiple data saving problem!

I’m trying to save leaderstats and other valeus in one script with the other values in a table so its easy, but its not working does anyone know why?

heres the script:

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

local playerValuesTable = {"Multiplier"}

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

	local number = Instance.new("IntValue")
	number.Name = "Number"
	number.Parent = leaderstats
	
	local playerValues = Instance.new("Folder")
	playerValues.Name = "PlayerValues"
	playerValues.Parent = player
	
	local playerUserId = "Player_" .. player.UserId
	local data = playerData:GetAsync(playerUserId)
	
	for index, value in pairs(playerValuesTable) do
		local newValue = Instance.new("IntValue")
		newValue.Name = value
		newValue.Parent = playerValues
		
		if data then
			newValue.Value = data
			number.Value = data
		else
			number.Value = 0
			newValue.Value = 0
		end
	end
end



local function onPlayerExit(player)
	local success, err = pcall(function()
		local playerUserId = "Player_" .. player.UserId
		playerData:SetAsync(playerUserId, player.leaderstats.Number.Value)
		for i, v in pairs(player.PLayerValues:GetChildren()) do
			playerData:SetAsync(playerUserId, v.Value)
		end
	end)

	if not success then
		warn('Could not save data!')
	end
end


game.Players.PlayerAdded:Connect(onPlayerJoin)
game.Players.PlayerRemoving:Connect(onPlayerExit)

The way you attempted to create the logic in your script is wrong, because of these two lines:

First, you saved the number value to the data store key, then…

… right after that line, you created a for loop which saves the player’s other values to the same data store key you used to save the previous data, overriding the old one.

What I would recommend to do is restructuring your data table. It could be in the form of a dictionary, where the first key consists of another dictionary, where it contains all the other leaderstat or other values you own, and then the second index of the main dictionary can be your other values.

This does seem very poorly setup. You should definitely be calling those Async functions within an individual protected call instead of just wrapping the entire function in one. You also are using SetAsync() many times which will overwrite the previous data. Instead, you should combine all your data into a table and send that along.

Didn’t see you had already replied but it looks like we shared quite similar recommendations.