Hello there! I am trying to create a datastore system and have encountered this issue: when the player leaves, the data needs to be saved and I basically need the following:
I have heard that a BindToClose function is needed and I searched for it and found this. I do not understand the for loop and have a question regarding it:
What does the for loop do?
Doesn’t it save the data of all players?
game:BindToClose(function(plr,)
for _, Player in pairs(game.Players:GetPlayers()) do -- What does this mean?
experienceStore:SetAsync("key", 1)
end
end)
Do I still need the PlayerRemoving function when using BindToClose?
I dont think you need PlayerRemoving in bind to close. Also the line gets all the players in the game and loops through them. GetPlayers() returns a table of all the players so it can loop through it, hope this helps!
Oh. I think I am understanding it now.
I use the BindToClose only for server shutdowns and the PlayerRemoving for a single player which leaves. Am I right?
It is better to have both. They are completely separate functions. BindToClose is for when the game is shutting down. When the game is shutting down, PlayerRemoving doesn’t always fire. This is why BindToClose runs and goes through every player to save their data (the for loop is to go through every player and save their data).
BindToClose like you stated runs the code when the server shuts down.
Also to answer your first question the code what it does the code does is when the server shuts down it loops through all the players and save the user data however part of your code makes no sense. You wrote “key” for the key part but the key should be some type of thing that can identify the player (for example there user ID or what some people do is user_[USERID]).
To answer your second question like what @Kaid3n22 stated sometimes when the game gets shut down the PlayerRemoving does not fire so it is good to have both. The BindToClose will only happen when the server shuts down so you still still need the PlayerRemoving so if someone just leaves not when the server shuts down can have there data saved.
This for loop runs a function for every player in the table [game.Players:GetPlayers() returns a table of players in the game]. Also, yes. Both of PlayerRemoving and BindToClose are needed for data loss and some else stuff.