Hi! So I am making a stop watch UI:
When you click the stopwatch button, it starts a 5 second countdown so you can get ready, and then starts the stopwatch when it hits 0. You can cancel the stopwatch in 2 ways: Stepping on a specific part I put in workspace, or you can just hit the button again.
I have two problems:
- The “Stop” part doesn’t actually stop the stopwatch
- The stopwatch doesn’t work after you stop and restart it.
Here is my script:
local button = script.Parent
local display = script.Parent.Display
local countdownTime = 5
local timer = 0
local countingDown = false
local stopConnection = nil
local function formatTime(time)
local minutes = math.floor(time / 60)
local seconds = time - (minutes * 60)
local milliseconds = math.floor((time % 1) * 1000)
return string.format("%02d:%02d:%03d", minutes, seconds, milliseconds)
end
button.MouseButton1Click:Connect(function()
if not countingDown then
countingDown = true
button.Text = "Cancel"
while countdownTime > 0 do
display.Text = formatTime(countdownTime)
countdownTime = countdownTime - 1
wait(1)
if not countingDown then
countdownTime = 5
display.Text = "Ready"
button.Text = "Start"
break
end
end
if countingDown then
display.Text = "00:00:000"
button.Text = "Stop"
local stopper = workspace:WaitForChild("Stopper")
local stopped = false
stopConnection = stopper.Touched:Connect(function(hit)
if hit.Parent and hit.Parent:FindFirstChild("Humanoid") then
stopped = true
end
end)
while not stopped do
timer = timer + 1/60
display.Text = formatTime(timer)
end
timer = 0
display.Text = "Stopped"
button.Text = "Start"
end
else
countingDown = false
countdownTime = 5
timer = 0
display.Text = "Ready"
button.Text = "Start"
if stopConnection then
stopConnection:Disconnect()
stopConnection = nil
end
end
end)
Thanks!