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

SetAsync not working on playerremoving?

-------
game.Players.PlayerRemoving:Connect(function(Player)
	print("Saving data..")
	local sidestats = Player:WaitForChild("sidestats")
	local leaderstats = Player:WaitForChild("leaderstats")
	---
	local stage = leaderstats:WaitForChild("Stage")
	store:SetAsync(Player.UserId.."Stage",stage.Value)
	print("Stage Saved")
	---
	local prestige = sidestats:WaitForChild("Prestige")
	store:SetAsync(Player.UserId.."Prestige",prestige.Value)
	print("Prestige Saved")
	---
	local coins = sidestats:WaitForChild("Coins")
	store:SetAsync(Player.UserId.."Coins",coins.Value)
	print("Coins Saved")
	---
	local pet = sidestats:WaitForChild("PlayerPet")
	store:SetAsync(Player.UserId.."PlayerPet",pet.Value)
	print("Pet Saved")
	---
end)
-------

None of this data is saving?

1 comment

0

put pcall when SetAysnc

2 answers

Check out https://developer.roblox.com/en-us/api-reference/function/DataModel/BindToClose - you want to make sure that when the last player leaves a server, that the server won't close without first saving their data.

If you intend to do the final save in PlayerRemoving instead of BindToClose as the link above shows, you will still need a BindToClose that waits until all saving is complete - the easiest way is to use a variable to keep track of how many threads are still saving and wait() until that's done:


local savingThreads = 0

game.Players.PlayerRemoving:Connect(function(Player)
	savingThreads += 1
	-- rest of your function here
	savingThreads -= 1
end)
game:BindToClose(function()
	repeat
		wait()
	until savingThreads == 0
end)

Tips:

  • There's no point in using WaitForChild because the moment your script yields [waits], the player will be gone. Those values should be there anyway, so it should be safe to simply access them directly (ex, local leaderstats = Player.sidestats.leaderstats)
  • You should save all your values for the same player in a table to prevent it costing you too many requests (since you only get so many per minutes, based on the number of players in the server, see https://developer.roblox.com/en-us/articles/Datastore-Errors)

I figured it out. It was due to me running it in studio

game:BindToClose(function()
	if RunService:IsStudio() then 
		wait(3)  
	end
end)

I added this and it works now.

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