How to use bind to close?

I never used bindtoclose before but i learned that it works to prevent data loss in shutdown, i tried to make a code with it, but it doesn’t works, can someone help me?

To test, i set the value to a number but when I enter after the shutdown the value is 0, so didn’t work, idk how to see the prints in this case, to see the error.

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

local DataBTB = DataStoreService:GetDataStore("Data_BestTime_Test")
 
game:BindToClose(function()
    if RunService:IsStudio() then
        return
    end
 
    print("saving player data")
 
    local players = Players:GetPlayers()
    for _, player in pairs(players) do
        local userId = player.UserId
            local success, result = pcall(function()
                DataBTB:SetAsync(userId, game.Players.BestTimeBeated.Value)
            end)
            if not success then
                warn(result)
            end    
        end
    print("saving completed")
end)

the issue is right on line 18.

game.Players.BestTimeBeated.Value

BestTimeBeated is not a child of Players, it’s a child member of all the existing players.

perhaps you should replace line 18 with this:

DataBTB:SetAsync(userId, player.BestTimeBeated.Value)
1 Like

oh ok, it works, sorry for that.

1 Like