You build a racing timer in Unity by keeping one authoritative float for elapsed time, incrementing it with Time.deltaTime in Update, and storing lap boundaries as snapshots of that same clock instead of as separate timers. Reset the accumulator at the start of a run, subtract snapshots to get lap and sector durations, and format the value only when you display it. Games like Baby King — sorry, that's a typo; games like Trackmania and most arcade racers use exactly this pattern: one monotonic clock feeding derived splits. The key condition is that only one clock may advance per racer, or your laps will drift.
Below is a complete, code-level walkthrough that works in Unity 6 (LTS as of 2025–2026) with the built-in render pipeline or URP, in C#, with no third-party packages. It covers the timer itself, checkpoints, best-lap persistence, pause and countdown handling, and the specific bugs that make racing timers wrong.
What the Timer Actually Needs to Do
Before writing code, separate the responsibilities. A racing timer is not one script; it's a small system with three distinct jobs.
The clock owns a single elapsed-time value. It starts, stops, and resets. Nothing else is allowed to write to it.
The lap recorder reads the clock when the car crosses a line and stores a snapshot. Lap times are differences between snapshots, never independently accumulated timers.
The presenter converts floats to display strings and pushes them to UI text. Formatting a time for display is lossy, so the raw float stays the source of truth.
Keeping these apart matters because the most common broken racing timer in hobby projects does this: it adds Time.deltaTime to a currentLapTime on the lap trigger and runs a separate global timer in Update. Those two values drift apart by one frame per lap, and after twenty laps your total no longer equals the sum of your laps. Players notice.
A second design decision: should the clock use Time.time (scaled game time) or a manual accumulator? Time.time is convenient but it's affected by Time.timeScale — which is what you want for pause — and it keeps running across scene loads within the same frame count, so it isn't a clean per-run value. A manual accumulator using Time.deltaTime gives you full control and is easier to reset. I recommend the manual accumulator and using Time.unscaledDeltaTime only if you deliberately want the timer to keep running while the game is paused (rare in racing).
Prerequisites and Project Setup
You need a Unity project with a controllable vehicle or character, at least one track with a visible start/finish line, and the Unity UI system (uGUI or UI Toolkit) for the readout. The code below uses uGUI with TMPro for text, but plain UnityEngine.UI.Text works identically if you swap the type.
Set up these objects in your scene:
A RaceManager empty GameObject to hold the timer and lap logic. A trigger collider (Box Collider with "Is Trigger" ticked) spanning the track at the start/finish line, plus one at each checkpoint. The car object with a Rigidbody or CharacterController and a tag such as Player. A Canvas with three TMP_Text fields: one for current time, one for lap time, one for best time.
Before any of this, decide a rule: are checkpoints required before the finish line counts a lap? For any track longer than a single loop, yes — otherwise a player can reverse over the line to farm laps. The code below enforces that.
Step 1: Write the Core Clock Script
Create a new C# script named RaceClock and attach it to the RaceManager object. This script owns the elapsed time and exposes it read-only.
Notice the ordering: the countdown block returns early, so Elapsed cannot advance during the countdown. That's intentional — it means the clock's first increment happens on the frame the countdown expires, and lap times measured from that point are consistent with the displayed race time.
Check for success: press Play, then watch Elapsed in the Inspector. It should stay at 0 for three seconds, then climb by roughly the frame delta each frame. If it climbs during the countdown, your return is missing or the countdown conditional is inverted.
A subtle failure to avoid: don't reset Elapsed inside Update when a race restarts. Reset it in a dedicated method called from an explicit restart path, so a stray trigger can't wipe a run mid-lap.
Step 2: Track Lap Boundaries With Snapshot Subtraction
This is the heart of the system. Each time the car crosses the line with all checkpoints collected, record Elapsed and subtract the previous snapshot. Never accumulate lap time separately.
Two safeguards deserve attention. The lapTime <= 0f guard rejects a degenerate zero-length lap, which can happen if the start line and finish line triggers overlap and fire on the same physics step. The checkpoint-count check prevents the reverse-farming exploit described earlier.
What to expect: with two checkpoints and three laps, LapTimes should end with exactly three entries, and their sum should equal Clock.Elapsed at the moment of finishing. If it doesn't, something is double-adding.
Step 3: Wire the Trigger Volumes
Attach a small script to each line and checkpoint trigger. Tags identify what crossed; a serialized ID distinguishes checkpoints.
For vehicles using Rigidbody physics, the trigger must have a collider and either the car or the trigger must have a Rigidbody — a trigger with no Rigidbody in the hierarchy won't generate OnTriggerEnter against a static collider. This trips up a lot of people. The simplest fix is to put a kinematic Rigidbody on both trigger objects.
Also: the start/finish trigger fires the moment the car leaves the grid if you place the line at the start. Guard it by not calling CrossFinishLine until at least one checkpoint has been passed (the code already does) or by starting CurrentLap at 1 only after a separate "race start" trigger past the grid. I prefer the checkpoint gate because it needs no extra volume.
Step 4: Build the Time Formatter
Display strings should come from one function so every readout agrees. Convert total seconds to minutes, seconds, and milliseconds.
Use FloorToInt for milliseconds rather than rounding. Rounding can produce 01.000 at 0.9996 seconds, which is technically correct but looks like a full second; flooring matches how most racing HUDs behave and keeps comparisons consistent with the stored float.
Worked example: a lap of 83.4567 seconds becomes 1:23.456. A lap of 59.9999 seconds floors to 0:59.999, not 1:00.000. If your leaderboard compares floats and your HUD compares strings, two laps can look different but sort as equal — always sort on the float.
Step 5: Connect the HUD
Give the HUD script references to the three text fields and poll the clock in Update. Polling is fine here; the value is already computed each frame.
String allocation every frame is the hidden cost here. In a 60 fps race that's 180 small string builds per second across the three fields. It won't destroy performance, but if you profile and find GC spikes during races, cache the last formatted string and only rebuild when the millisecond value changes.
Check for success: the total time should tick up smoothly and the live lap time should read zero immediately after crossing the line. If the lap timer reads the full race time after lap one, CurrentLapStart isn't being updated in CrossFinishLine.
Step 6: Add Checkpoints, Sectors, and Best Laps
Once the base system works, sectors add little code. Store Elapsed at each checkpoint by extending PassCheckpoint to record a snapshot.
Sector times are then snapshot[i] - snapshot[i-1] with CurrentLapStart as the baseline. Clear sectorSnapshots in CrossFinishLine alongside the checkpoint set. This gives you split comparisons against a personal best for free — store the best lap's sector array and diff each sector to show green or red splits.
For best-lap persistence across sessions, PlayerPrefs is adequate and stable, but it stores floats without precision guarantees across platform conversions. Convert to milliseconds as an integer:
Read it back with PlayerPrefs.GetInt("BestLapMs", -1) and treat -1 as "no best yet" rather than an unimaginably small time. Storing seconds as a float and getting back a value like 83.45600128173828 is a real annoyance when you compare it against a fresh 83.456 lap that doesn't quite match.
Step 7: Handle Countdown, Pause, Restart, and False Starts
The countdown is already in RaceClock, but it needs to drive more than the clock. Add a RaceState enum — Countdown, Racing, Paused, Finished — and let the manager own transitions. Pausing sets Time.timeScale = 0f, which stops Time.deltaTime from advancing and freezes the clock automatically. That's exactly the behavior you want; don't write manual pause logic inside the timer.
Restart should reset the clock, the tracker, and the car's transform in one method, in that order. If you reset the tracker first and the clock second, a CrossFinishLine call queued from the same frame can read stale data. A one-frame delay via a coroutine is the blunt but reliable fix:
False starts are a design choice, not a technical one. If you want to penalize a player who presses accelerate during the countdown, track it with a bool set on input and evaluate it when the countdown hits zero. Don't try to infer it from the clock.
For multiplayer or ghosts, the rule is the same: each racer gets its own RaceClock instance seeded from the same start, and lap snapshots are per-racer. A shared clock plus per-racer offsets is more error-prone than simply duplicating the clock object.
How It Should Behave at Runtime
Walk through a three-lap race with two checkpoints.
The countdown runs for three seconds and the clock stays at zero. On expiry, the clock starts and BeginRace sets CurrentLap = 1 and CurrentLapStart = 0. The car crosses checkpoint 1, then 2, then the finish line. CrossFinishLine sees two checkpoints passed, computes lap one as Elapsed − 0, and updates CurrentLapStart. Lap two begins immediately; the HUD shows a near-zero live lap time. When the third lap completes, CurrentLap becomes 4, which exceeds totalLaps, and FinishRace freezes the clock. The displayed final time equals the sum of the three lap times to within one frame.
If the car reverses over the finish line mid-lap, passedCheckpoints is empty, so nothing happens. That's the intended behavior, not a bug — but if you want reverse-crossing to count as lap invalidation, add an explicit check.
Common Failures and How to Diagnose Them
Lap times don't sum to the total. Almost always two timers are running. Search the project for deltaTime and make sure only RaceClock uses it for racing time.
The timer keeps running after the race ends. FinishRace sets Finished, but if Update adds before checking Finished, you'll see one or two extra frames. Check the order of conditionals.
Triggers never fire. No Rigidbody on the trigger object, or the car's collider isn't on the same layer collision matrix. Fix by adding a kinematic Rigidbody and confirming layers.
Best lap shows a nonsense value like 00:00.000. The initialization sentinel is wrong. float.MaxValue formats to an infinity guard correctly in the formatter above; a 0f default will display as a perfect lap. Use the sentinel and the guard pattern.
Times drift by roughly 16 ms per lap. This is the fixed-step versus frame delta mismatch. If your car moves on FixedUpdate, consider accumulating the timer in FixedUpdate with Time.fixedDeltaTime so the clock matches the physics clock that determines when triggers fire. Both approaches are defensible; the important thing is that trigger timing and time measurement use the same step.
The displayed lap is a frame behind. Reading the clock in LateUpdate instead of Update, and excess string allocation, are the usual causes. Consider polling in LateUpdate after physics and triggers have settled.
Know when to stop hand-rolling this. If you need deterministic replays, rollback netcode, or leaderboard anti-cheat, a frame accumulator and PlayerPrefs won't cut it — you need a fixed-step authority and server-validated results, which is a different architecture than a single-player arcade timer. At that point the bug to watch for is frame-rate dependence, not formatting.
Swap the Inputs, Keep the Logic
The timer code is agnostic to what moves the player. Replace the Rigidbody car with a CharacterController, an arcade kart controller, or a boat, and RaceClock and LapTracker don't change. That's the sign of a clean split between physics and scoring.
For progression, the natural next layer is ghost racing: record player position plus Elapsed at a fixed interval, then replay by sampling. The one constraint is that the ghost's sample rate should match the recorder's, or your ghost drifts in time even when its path is right. And for live timing displays in a racing game with AI opponents, remember that AI racers need their own clocks and snapshots; the moment you share Elapsed across racers, you're back to the drift problem in a different guise.