Menu
CoddyTech

Time Trial

Part of the Building Real Games section of Coddy's Unity journey. Lesson 55 of 56.

A time trial across a garden. The runner starts at one end with ten seconds on the clock and has to reach the white goal at the far end, around a hedge, before the time runs out. Golden clocks on the way buy a few more seconds each. When the time is nearly gone the clock turns red; when it is gone, the track starts over. Reach the goal in time and the game moves on to the Finish scene.

Write two scripts: Runner on the runner, a CharacterController, and Race on the Race object.

challenge icon

Challenge

Hard

The build has two scenes, Track and Finish. On the track, the clocks are tagged Clock and the goal Goal; both are triggers.

The Inspector gives Runner speed (6), gravity (-9.81) and race (the Race script).

  • The project's Move action runs the runner at speed units per second: right and left along x, up and down along z. It falls with gravity and moves only with controller.Move, so the hedge stops it.
  • Running into a clock uses it up and gives the race its bonus. Running into the goal finishes the race.

The Inspector gives Race timeLimit (10), bonus (3) and timeText.

  • The time left starts at timeLimit and goes down by the real time that passes. timeText shows it with one decimal, as Time: 7.4, in white, and in red (Color.red) while less than 3 seconds are left.
  • Each clock adds bonus seconds.
  • When the time reaches 0, log Time's up! and load the track again from the start.
  • When the race is finished in time, log the time left, as Finished with 4.2 s left, and load the Finish scene.

Press Play and beat the clock, then Check.

Try it yourself

using UnityEngine;
using UnityEngine.SceneManagement;
using TMPro;

public class Race : MonoBehaviour
{
    public float timeLimit = 10f;
    public float bonus = 3f;
    public TMP_Text timeText;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Building Real Games