I think it is from ReplicatedFirst, I guess. So I was making a script to save a player's data when leaving. I had to save a tool that a player might have. There are two chances. One is not holding the tool and one is holding. I know that it goes to player.Backpack when not held, and if it is held, it will stay inside the player's character. So I used player.Character to get the character, I tested it, but it didn't work. The output said attempt to a nil value 'Character' which I noticed that the Character is already gone. I think I remember there was a method: 'Even though the (last) player leaves, the server stays open so that they can save data' I think heard it from a YouTube video but I don't remember what channel it was, and what video it was so can anybody help???
Short: Way to leave the server open though the player leaves
:BindToClose()
is a function that will bind a function to the closing of the server. PlayerRemoved
may seem similar to this when the last player leaves, however shutting down the server is prioritized, and PlayerRemoved
may fail to fire.
The function you bind in :BindToClose()
can wait a maximum of 30 seconds before the shutdown is forced. You could use this to make sure data is saved in a datastore.
Here is a short example on how it would work:
local dataStoreService = game:GetService("DataStoreService") local players = game:GetService("Players") function loadData(player) -- load your data end function saveData(player) -- save your data end players.PlayerAdded:Connect(function(player) loadData(player) end) players.PlayerRemoving:Connect(function(player) saveData(player) end) game:BindToClose(function() local remaining = players:GetChildren() for _, player in pairs(remaining) do saveData(player) end end)