Saving data when shutting down

I want to save data when the game shuts down and I included a game:BindToClose but that doesn’t seem to work, can someone help?

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

local dataStore = DataStoreService:GetDataStore("TimeDataStore")
local timeCounters = {}

local function updateTime(player)
	local userId = player.UserId
	if not timeCounters[userId] then
		timeCounters[userId] = 0
	end
	timeCounters[userId] = timeCounters[userId] + 1
end

local function resetTime(player)
	local userId = player.UserId
	timeCounters[userId] = 0
	local timeLabel = getTimeLabel(player)
	if timeLabel then
		timeLabel.Text = "Time: " .. timeCounters[userId]
	end
end


local updatingtime = coroutine.create(function()
	while true do
		wait(1)
		for _, player in ipairs(Players:GetPlayers()) do
			updateTime(player)
		end
	end
end)
coroutine.resume(updatingtime)

local function getTimeLabel(player)
	local character = player.Character
	if character then
		local head = character:FindFirstChild("Head")
		if head then
			local billboardGui = head:FindFirstChild("TimeBillboardGui")
			if billboardGui then
				return billboardGui:FindFirstChild("TimeLabel")
			end
		end
	end
	return nil
end

local function createBillboardGui(player, timeCounter)
	local character = player.Character or player.CharacterAdded:Wait()
	local humanoid = character:WaitForChild("Humanoid")
	local head = character:WaitForChild("Head")

	local existingBillboardGui = head:FindFirstChild("TimeBillboardGui")
	if existingBillboardGui then
		existingBillboardGui:Destroy()
	end
	local billboardgui1 = ServerStorage.BillboardGui
	local billboardGui = billboardgui1:Clone()
	billboardGui.Name = "TimeBillboardGui"
	billboardGui.Adornee = head
	billboardGui.AlwaysOnTop = true

	local timelabel1 = ServerStorage.BillboardGui.TextLabel
	local timeLabel = timelabel1:Clone()
	timeLabel.Name = "TimeLabel"
	timeLabel.BackgroundTransparency = 1
	timeLabel.Text = "Time: " .. timeCounter
	timeLabel.Font = Enum.Font.SourceSansBold
	timeLabel.TextColor3 = Color3.new(1, 1, 1)
	timeLabel.BorderSizePixel = 2
	timeLabel.BorderColor3 = Color3.new(0, 0, 0)
	timeLabel.Parent = billboardGui

	billboardGui.Parent = head

	humanoid.Died:Connect(function()
		print(player.Name, "died. Resetting timeCounter.")
		resetTime(player)
	end)
end

Players.PlayerAdded:Connect(function(player)
	createBillboardGui(player, timeCounters[player.UserId] or 0)

	player.CharacterAdded:Connect(function()
		createBillboardGui(player, timeCounters[player.UserId] or 0)
	end)

	player.CharacterRemoving:Connect(function()
		-- Don't reset time on leaving
		local userId = player.UserId
		local counter = timeCounters[userId] or 0
		local success, error = pcall(function()
			dataStore:SetAsync(tostring(userId), counter)
		end)
		if not success then
			warn("Failed to save time counter for UserID " .. userId .. ":", error)
		end
	end)
	game:BindToClose(function()
		for _, player in ipairs(Players:GetPlayers()) do
			local userId = player.UserId
			local counter = timeCounters[userId] or 0
			local success, error = pcall(function()
				dataStore:SetAsync(tostring(userId), counter)
			end)
			if not success then
				warn("Failed to save time counter for UserID " .. userId .. ":", error)
			end
		end
	end)
end)
while true do
	wait(1)
	for _, player in ipairs(Players:GetPlayers()) do
		local timeLabel = getTimeLabel(player)
		if timeLabel then
			local userId = player.UserId
			local timeCounter = timeCounters[userId] or 0
			timeLabel.Text = "Time: " .. timeCounter
		end
	end
end

I would take a look at this Players | Documentation - Roblox Creator Hub, bindtoclose is the server shutting down not the player leaving.

Maybe try putting the BindToClose outside the PlayerAdded since that might be causing problems?

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.