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
HardThe 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
speedunits per second: right and left along x, up and down along z. It falls withgravityand moves only withcontroller.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
timeLimitand goes down by the real time that passes.timeTextshows it with one decimal, asTime: 7.4, in white, and in red (Color.red) while less than 3 seconds are left. - Each clock adds
bonusseconds. - 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;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Building Real Games
2Buttons and Screens
Buttons and onClickLambdasWiring in the InspectorPanels On and OffHealth BarsRecap: Upgrade Shop5Saving with PlayerPrefs
Save a NumberLoad with a DefaultHigh ScoreSave SettingsRecap: Coins in the Bank3The Game Manager
One Script Runs the GameThe SingletonGame StatesSwitching on the StateRecap: Round Manager6Project: Endless Runner
Three LanesObstacles Ahead9The New Input System
Two Input SystemsKeyboard and MousePressed This FrameInput ActionsRecap: Input Swap