Data store not working

My data store is not working and i don’t know what’s wrong with it

local DataStoreService = game:GetService("DataStoreService")

local playerData = DataStoreService:GetDataStore("PlayerData")



local function onPlayerJoin(player)

	local leaderstats = Instance.new("Folder")

	leaderstats.Name = "leaderstats"

	leaderstats.Parent = player



	local money = Instance.new("IntValue")

	money.Name = "Money"

	money.Parent = leaderstats



	local exp = Instance.new("IntValue")

	exp.Name = "Experience"

	exp.Parent = leaderstats



	local playerUserId = "Player_" .. player.UserId

	local data = playerData:GetAsync(playerUserId)

	if data then

		money.Value = data['Money']

		exp.Value = data['Experience']

	else


		money.Value = 0

		exp.Value = 0

	end

end



local function create_table(player)

	local player_stats = {}

	for _, stat in pairs(player.leaderstats:GetChildren()) do

		player_stats[stat.Name] = stat.Value

	end

	return player_stats

end



local function onPlayerExit(player)



	local player_stats = create_table(player)

	local success, err = pcall(function()

		local playerUserId = "Player_" .. player.UserId

		playerData:SetAsync(playerUserId, player_stats)

	end)



	if not success then

		warn('Could not save data!')

	end

end



game.Players.PlayerAdded:Connect(onPlayerJoin)

game.Players.PlayerRemoving:Connect(onPlayerExit)

No errors at all + API services are enabled

1 Like

The code looks sound.
Have you tried adding some print lines on each event when attempting to read/write the data?

1 Like

Already did that, I will try it again

For some reason the PlayerRemoving event doesn’t fire in studio if you stop play testing (likely doesn’t fire fast enough), you can add a game:BindToClose() event which loops through all the players & saves their data

1 Like