Datastore Binding to Close

Hello, I’m using Datastore and I was wondering how I would bind to close for my stats?
here is the code:

``local DataStoreService = game:GetService(“DataStoreService”)

local currencyStore = DataStoreService:GetDataStore(“currencyStore”)

game.Players.PlayerAdded:Connect(function(player)
local produce = Instance.new(“Folder”)
produce.Name = “Produce”
produce.Parent = player

local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player

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

local carrots = Instance.new("IntValue")
carrots.Name = "Carrots"
carrots.Parent = produce
carrots.Value = 0

local corn = Instance.new("IntValue")
corn.Name = "Corn"
corn.Parent = produce
corn.Value = 0

local eggplant = Instance.new("IntValue")
eggplant.Name = "Eggplant"
eggplant.Parent = produce
eggplant.Value = 0

-----------------------------------------------
local farmCash = Instance.new("IntValue", leaderstats)
farmCash.Name = "Cash"
farmCash.Parent = leaderstats
farmCash.Value = 0
-----------------------------------------------
local data
local success, errormessage = pcall(function()
	data = currencyStore:GetAsync(player.UserId.."-cash")
end)
if success then
	farmCash.Value = data
	print("Successfully loaded data!")
else
	print("A problem occured while loading data")
	warn(errormessage)
end
-----------------------------------------------

end)

game.Players.PlayerRemoving:Connect(function(player)

local success, errormessage = pcall(function()
	currencyStore:SetAsync(player.UserId.."-cash", player.leaderstats.Cash.Value)
end)
if success then
	print("Player Data was saved!")
else
	print("There was a error while saving data")
	warn(errormessage)
end

end)``

Connect the function that you use for playerRemoving to Bind to close. Here is the documentation.

I’m sorry, but I don’t see how run service is of any use…

This is the issue:
``
game:BindToClose(function()
for i, v in pairs(game.Players:GetChildren) do
– I don’t know what come here
end
end)

Do this:

game:BindToClose(function()
for _, Player in pairs(game.Players:GetPlayers()) do
DataStore:SetAsync(PlayerKeyHere, Data)
end)
1 Like