SetAsync() doesn't work?!

Hi, recently, I was trying to make a datastore for player points, the issue here is that when the player leaves, PlayerRemoving event works but it doesn’t save. I searched for solutions but I didn’t find/understand. I tried to determine where exactly where the problem then I found out that it is in that part (PlayerRemoving event).

local dataStoreService = game:GetService("DataStoreService")
local myDataStore = dataStoreService:GetDataStore("playersPointSStorage")

game.Players.PlayerAdded:Connect(function(player)
	
	local leaderstatefolder = Instance.new("Folder")
	leaderstatefolder.Name = "leaderstats"
	leaderstatefolder.Parent = player
	
	local Points = Instance.new("IntValue")
	Points.Name = "Points"
	Points.Parent = leaderstatefolder
	
	local playerId = player.UserId
	
	--load Data
	
	local data 
	local success, errorMassage = pcall(function() 
		data = myDataStore:GetAsync(playerId) 
	
	end)
	
	if success then
		Points.Value = data  to data (Our DataStore)

	end

end)

--------------------------------------------------------------------------------

game.Players.PlayerRemoving:Connect(function(player)
	local playerId = player.UserId
	
	local data = player.leaderstats.Points.Value
	
	local success, errorMassage = pcall(function()
		myDataStore:SetAsync(playerId, data)
		
	end)
	
	if success then
		print("The points has saved")
	else
		print("The points hasn't saved")
		warn(errorMassage)
	end
	
end)

Sorry if I missed something stupid, I’m a beginner.
Note: The points were added by clicking a part in the studio.

3 Likes

try testing in a main game if it doesn’t work try using

game:BindToClose(function()

-- saving part here

end)
2 Likes

Does errorMassage say anything in the Output?

1 Like

also i would recommend making the saving part a function so you can do this

local function save(player)
local playerId = player.UserId
	
	local data = player.leaderstats.Points.Value
	
	local success, errorMassage = pcall(function()
		myDataStore:SetAsync(playerId, data)
		
	end)
	
	if success then
		print("The points has saved")
	else
		print("The points hasn't saved")
		warn(errorMassage)
	end
end



game:BindToClose(function()
for i , v in pairs(game.Players:GetPlayers()) do
save(v)
end
end)
3 Likes

It’s likely that the value of Points is nil.

2 Likes

Were the points added on the server or the client?

2 Likes

Have you tried using tostring(player.UserId)?

2 Likes

It saves when I testing in the main game but it doesn’t while I am in the studio and that’s why it doesn’t print “The points has saved” but why didn’t it print “the points hasn’t saved” and the warn? That’s weird.

I decide to use this way instead of mine, so congrats! you are the solution.

1 Like

your welcome happy to help if you do want it to save in studio you can go to game settings in studio go to options and then turn on enable api services

1 Like