✓ Accepted answer
#Brief Definition
BindToClose will fire once there are no players on the server and the server needs to shut down. It will stop the server from closing for up to 30 seconds so that it has time to run the function. Once the function runs or 30 seconds have passed, the server will close.
#OnClose vs BindToClose
BindToClose is similar to OnClose (now deprecated) in that they both stall the server from shutting down. The reason why we use BindToClose rather than OnClose is that there was a problem with OnClose. The issue was that after the function was over, it would immediately close the game, even if there were other scripts that were also using OnClose. BindToClose will not close the game until every single function ran (or 30 seconds is over).
game.OnClose = function()
print("Closing Server")
end
game.OnClose = function()
CleanUp()
wait(3)
SaveData()
print("Finished")
end
Closing Server
In the above example, script 1 ran and printed a message in the output, but the second script did not get to finish!
game:BindToClose(function()
print("Closing Server")
end)
game:BindToClose(function()
CleanUp()
wait(3)
SaveData()
print("Finished")
end)
Closing Server
Finished
Now, both functions ran to completion because the server waited for both functions to finish before closing.
#DataStores and its Relationship with BindToClose
It's recommended that you save all your unsaved data with BindToClose in case of an unexpected crash or close. Here is an example of how that would look. In this example, we are making a tycoon game and we're saving cash.
local DataStoreService = game:GetService("DataStoreService")
local money = DataStoreService:GetDataStore("Cash")
game:BindToClose(function()
if not game:GetService("RunService"):IsStudio() then
local players = game:GetService("Players"):GetPlayers()
for _,v in pairs(players) do
local userId = v.UserId
local success, result = pcall(function()
Money:SetAsync(userId, v.leaderboard.Cash.Value)
end)
if not success then
warn(result)
end
end
end
print("Finished")
end)
Finished
Leaderboards are probably legacy by now. I'm just using them as an example.
Hope it helps!
3 comments
Your data was placed into the server when you joined. Until you delete the data you have collected in your scripts, it is on the server. It never left.
BindToClose is not for when you leave the game/disconnect either. PlayerRemoving is for when you disconnect.
BindToClose is for when the server is going to shut down. The game crashing would not be saved with BindToClose.