Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Stay the server open for few seconds when the player leaves. Can anybody help?

Asked by 5 years ago
Edited 5 years ago

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

0
Oh wait, got it, it was :BindToClose() but can anybody tell me an example tree_tree00 48 — 5y
0
Do you use wait()? tree_tree00 48 — 5y
0
and where do you put the script? tree_tree00 48 — 5y

1 answer

Log in to vote
0
Answered by
megukoo 877 Moderation Voter
5 years ago

: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)
Ad

Answer this question