im making a script(s) that will update a textlabel based on how long the player is alive for but it updates once when the player is dead and the timer will only start again when respawned
serverside counter
-- TimeTrackerScript.lua (Place this in ServerScriptService)
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local updateTimeEvent = ReplicatedStorage:WaitForChild("RemoteEvents"):WaitForChild("UpdateTimeAlive")
-- Function to format the time
local function formatTime(seconds)
local hours = math.floor(seconds / 3600)
local minutes = math.floor((seconds % 3600) / 60)
local seconds = seconds % 60
if hours > 0 then
return string.format("%dh %dm %ds", hours, minutes, seconds)
elseif minutes > 0 then
return string.format("%dm %ds", minutes, seconds)
else
return string.format("%ds", seconds)
end
end
-- Function to update player's time alive
local function updatePlayerTimeAlive(player, secondsAlive)
local formattedTime = formatTime(secondsAlive)
player.leaderstats.TimeAlive.Value = formattedTime
updateTimeEvent:FireClient(player, formattedTime)
end
-- Function to handle player joining
local function onPlayerAdded(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local timeAlive = Instance.new("StringValue")
timeAlive.Name = "TimeAlive"
timeAlive.Value = "0s"
timeAlive.Parent = leaderstats
local secondsAlive = 0
local timeAliveConnection
-- Start tracking time
timeAliveConnection = game:GetService("RunService").Heartbeat:Connect(function(dt)
secondsAlive = secondsAlive + dt
updatePlayerTimeAlive(player, math.floor(secondsAlive))
end)
-- Reset time on player death
player.CharacterAdded:Connect(function(character)
character:WaitForChild("Humanoid").Died:Connect(function()
secondsAlive = 0
updatePlayerTimeAlive(player, secondsAlive)
end)
end)
-- Clean up on player removal
player.AncestryChanged:Connect(function()
if not player:IsDescendantOf(game) then
if timeAliveConnection then
timeAliveConnection:Disconnect()
end
end
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
local script
-- TimeAliveClient.lua (Place this in StarterPlayerScripts)
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local updateTimeEvent = ReplicatedStorage:WaitForChild("RemoteEvents"):WaitForChild("UpdateTimeAlive")
updateTimeEvent.OnClientEvent:Connect(function(timeAlive)
-- You can display the updated timeAlive value on the player's UI if needed
print("Updated Time Alive: " .. timeAlive)
local playerGui = game.Players.LocalPlayer:FindFirstChildOfClass("PlayerGui")
if playerGui then
local timeAliveLabel = playerGui:FindFirstChild("TimeAliveLabel")
if timeAliveLabel then
timeAliveLabel.Text = "Time Alive: " .. timeAlive
else
warn("TimeAliveLabel not found in PlayerGui")
end
else
warn("PlayerGui not found")
end
end)