So im trying to make something like a “Time alive counter” and this was all i could do with my knowledge of scripting and i need to make it so that it stops going on when the player dies and not restart or just go on with the counting. Ive been trying to find the solution for 3 hours or so.
Im more experience with modelling than scripting so even if this might be a super basic thing it will help a ton.
You’d want to be using a localscript first, and check out the docs for more help.
If you’re looking for an instant answer, I haven’t checked or tested this but here’s some code:
-- Get the Player and their Character
local player = game.Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
-- Variables to track time
local startTime = nil
local aliveTime = 0
-- Function to update alive time
local function updateAliveTime()
if startTime then
aliveTime = aliveTime + (tick() - startTime)
startTime = tick()
end
end
-- Update alive time every frame
game:GetService("RunService").RenderStepped:Connect(updateAliveTime)
-- Start the timer when the character spawns
character.Humanoid.Died:Connect(function()
startTime = nil
aliveTime = 0
end)
-- Print alive time every second (optional)
while true do
wait(1)
print("Alive Time: " .. aliveTime)
end
local x = 0
local counting = true
while counting and x < 10000000000000000000000000000000000000000 do
wait(1)
x = x + 1
end
script.Parent.Text = tostring(x)
In this version, the variable x is incremented by 1 within the while loop using x = x + 1. The loop will continue as long as counting is true and x is less than the specified large number.
count up in a seperate thread and then connect some death and spawn events to start and stop the timer
a thread runs seperately from the rest of the script almost like its in a different script, so any wait() inside of it doesnt effect the rest
local count = 0
local counting = true
task.spawn(function()
while true do
if counting == true then count += 1 end
task.wait(1)
end
end)
local plr = game.Players.LocalPlayer -- this only work in a local script
--when dies
plr.Character.Humanoid.Died:Connect(function())
counting = false
end
--when they spawn
plr.CharacterAdded:Connect(function()
counting = true
end
Syntax error: The line count += 1 should be count = count + 1. The += operator is not supported in Lua.
Missing closing parentheses: The examplePlr.CharacterAdded:Connect(function() statement is missing a closing parenthesis.
Here’s the corrected code:
local count = 0
local counting = true
task.spawn(function()
while true do
if counting == true then
count = count + 1
end
task.wait(1)
end
end)
-- When the player dies
examplePlr.Character.Humanoid.Died:Connect(function()
counting = false
end)
-- When the player spawns
examplePlr.CharacterAdded:Connect(function()
counting = true
end)