I heard it’s important for saving data so how would I use it?
Have you at least checked the API first…?
I have some code that I use bindtoclose in studio, to save player data if a studio window is closed, but PlayerRemoving for the game… I’ll just post that section, for an example (I was using some of this for a simulator):
game.Players.PlayerRemoving:Connect(function(plr)
if plr:FindFirstChild("leaderstats") and plr.leaderstats:FindFirstChild("Coins") then
SaveFizzData(plr,plr.leaderstats["Fizz"],false)
SaveCandyData(plr,plr.leaderstats["Candy"],false)
SaveCoinData(plr,plr.leaderstats["Coins"],true) -- need to at least Force on ONE stat to save them all
end
end)
if not game:GetService("RunService"):IsStudio() then
game:BindToClose(function()
for _,plr in pairs(game:GetService("Players")) do
if plr:FindFirstChild("leaderstats") and plr.leaderstats:FindFirstChild("Coins") then
--SaveData(plr,plr.leaderstats["Coins"])
SaveFizzData(plr,plr.leaderstats["Fizz"],false)
SaveCandyData(plr,plr.leaderstats["Candy"],false)
SaveCoinData(plr,plr.leaderstats["Coins"],true) -- need to at least Force on ONE stat to save them all
end
end
wait(10)
end)
end
Loop through the players and save their data through a datastore.
game:BindToClose(function() -- this function will fire once the game has shutdown
for _, player in ipairs(Players:GetPlayers()) do -- loop through players
xpcall(function() -- use a pcall to catch any errors
datastore:UpdateAsync(player.UserId, function() -- save your data through updateasync
return newdata -- return back the new data that were saying
end)
end, warn)
end
end)
(also the api page does have a example of how to save using bindtoclose)
I had that exact same code except for the xpcall and it didn’t run. So I made this post. For me it didn’t print the player in the loop
Why do you need to check if they aren’t in the studio?
Maybe try testing inside game? I’ve had a problem where data didn’t save unless in live game for some weird reason.
It ran but it didn’t save the data.
Per the documentation, you use BindToClose if the server shutsdown, but otherwise it won’t work in studio, but the client shutting down when the player leaves is good enough.
You might also check this link on the same topic: