PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience

Saving player data before shutting down

Saving player data before shutting down

Sep 19 2018, 4:24 AM PST

The following code sample is an example of how DataModel/BindToClose can be used to save player data in the event of a server shutdown. In this example, player data is stored in a dictionary named playerData with Player/UserId|UserIds as keys.

local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local RunService = game:GetService("RunService")

local dataStore = DataStoreService:GetDataStore("Data")

local playerData = {
    -- [UserId] = data
}

game:BindToClose(function()
    -- if the current session is studio, do nothing
    if RunService:IsStudio() then
        return
    end

    print("saving player data")

    -- go through all players, saving their data
    local players = Players:GetPlayers()
    for _, player in pairs(players) do
        local userId = player.UserId
        local data = playerData[userId]
        if data then
            -- wrap in pcall to handle any errors
            local success, result = pcall(function()
                -- SetAsync yields so will stall shutdown
                dataStore:SetAsync(userId, data)
            end)
            if not success then
                warn(result)
            end    
        end
    end

    print("completed saving player data")

end)