Data only sometimes saving

Hello, I have a datastore script made but it only saves the data sometimes, not every time.

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

game.Players.PlayerAdded:Connect(function(player) -- Runs when players join
	local StatsFolder = Instance.new("Folder")  --Sets up leaderstats folder
	StatsFolder.Name = "Stats"
	StatsFolder.Parent = player

	local PPC = Instance.new("IntValue") --Sets up value for leaderstats
	PPC.Name = "PointPerClick"
	PPC.Parent = StatsFolder
	
	local CFR = Instance.new("IntValue") --Sets up value for leaderstats
	CFR.Name = "ClicksNeededForRebirth"
	CFR.Parent = StatsFolder
	
	local leaderstats = Instance.new("Folder")  --Sets up leaderstats folder
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	
	local Clicks = Instance.new("IntValue") --Sets up value for leaderstats
	Clicks.Name = "Clicks"
	Clicks.Parent = leaderstats

	local playerUserId = "Player_" .. player.UserId  --Gets player ID
	local data = playerData:GetAsync(playerUserId)  --Checks if player has stored data
	if data then
		-- Data exists for this player
		PPC.Value = data['PointPerClick']
		CFR.Value = data['ClicksNeededForRebirth']
		Clicks.Value = data['Clicks']
	else
		-- Data store is working, but no current data for this player
		PPC.Value = 1
		Clicks.Value = 0
		CFR.Value = 100
	end
end)

local function create_table(player)
	local player_stats = {}
	player_stats[player.leaderstats.Clicks.Name] = player.leaderstats.Clicks.Value
	player_stats[player.Stats.PointPerClick.Name] = player.Stats.PointPerClick.Value
	player_stats[player.Stats.ClicksNeededForRebirth.Name] = player.Stats.ClicksNeededForRebirth.Value
	return player_stats
end

game.Players.PlayerRemoving:Connect(function(player)  --Runs when players exit
	local player_stats = create_table(player)
	local success, err = pcall(function()
		local playerUserId = "Player_" .. player.UserId
		playerData:SetAsync(playerUserId, player_stats)
		print("Data Saved") --Saves player data
	end)
	if not success then
		warn('Could not save data!')
	end
end)

Are you play testing this in a server with multiple users? It’s possible the server is closing before it can save the player data.

I’m testing it in studio, which means that could be possible

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