local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local DataStoreService = game:GetService("DataStoreService")
-- Define your DataStore
local personalBestDataStore = DataStoreService:GetDataStore("PersonalBest")
local startTime = 0
local currentTime = 0
local timerStopped = true
local personalBestValue = math.huge
local textLabel = script.Parent
local player = Players.LocalPlayer
-- Function to update UI with current timer and personal best
local function updateUI()
textLabel.Text = string.format("Timer: %.3f\nPersonal Best: %.3f", currentTime, personalBestValue)
end
-- Function to start the timer
local function startTimer()
if timerStopped then
timerStopped = false
startTime = tick()
currentTime = 0
RunService.RenderStepped:Connect(function()
if not timerStopped then
currentTime = tick() - startTime
updateUI()
end
end)
end
end
-- Function to stop the timer and update personal best if necessary
local function stopTimer()
if not timerStopped then
timerStopped = true
if currentTime > 0 and currentTime < personalBestValue then
personalBestValue = currentTime
if player then
-- Update DataStore with new personal best
local success, err = pcall(function()
personalBestDataStore:SetAsync("Player_" .. player.UserId, personalBestValue)
end)
if not success then
warn("Failed to save personal best:", err)
end
end
end
updateUI()
end
end
-- Function to load personal best from DataStore
local function loadPersonalBest()
if player then
local success, storedBest = pcall(function()
return personalBestDataStore:GetAsync("Player_" .. player.UserId)
end)
if success and storedBest then
personalBestValue = storedBest
end
end
end
-- Connect start and stop functions to appropriate triggers
workspace.StartTimer.Touched:Connect(startTimer)
workspace.EndPart.Touched:Connect(stopTimer)
-- Handle player respawn or rejoin
if player then
player.CharacterAdded:Connect(function(character)
-- Reset timer on respawn/rejoin
currentTime = 0
updateUI()
-- Load personal best on respawn/rejoin
loadPersonalBest()
end)
end
-- Initialize UI with current personal best on script load
loadPersonalBest()
updateUI()