Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

DataStore:SetAsync does not work on PlayerRemoved?

In my game, I've implemented a DataStore feature that saves and loads points. Everything seems to be working fine until I attempt to SetAsync in a PlayerRemoved event. ONLY when I'm in studio does this happen. I've even tried saving data automatically after 5 seconds after joining, and that works. The code seems to stop at SetAsync and not run any further after I stop running the game in Studio. This works in the published game though, and I have Studio API on. if it helps, I followed along with TheDevKing's tutorial on Data Persistence. Here's the code:

local data_service = game:GetService("DataStoreService")
local data_store = data_service:GetDataStore("MyData")

-- There is a setasync function before this that works fine

game.Players.PlayerRemoving:Connect(function(plr)
	local user_id = plr.UserId
	local data = plr.leaderstats.Points.Value
	
	local success, error_msg = pcall(function()
		data_store:SetAsync(user_id, data)
	end)
	if success then
		print("Data saved successfully!")
	else
		print("Data error!")
		warn(error_msg)
	end
end)

Is there any way to fix this, such as making it faster?

1 comment

0

Please code block all of your code.

1 answer

✓ Accepted answer

The problem with Players.PlayerRemoving is that it doesn't count for the last player in the server. When the last player leaves, the game shuts down straight away. A way to solve that is to use game:BindToClose(). game:BindToClose() allows the function to run for 30 seconds before the server shuts down. (In other words, make sure that your function is fast enough or else the game shuts down.) Here's the link to more information about DataModel:BindToClose() (Note: This link also includes an example on how to save your data.)

1 comment

0

While the DevKing is a great Roblox Studio YouTuber, the video about DataStores is now considered somewhat outdated since it doesn't include game:BindToClose().

This discussion is preserved as it was. New answers, comments, and votes are closed.