Best Time
Part of the Building Real Games section of Coddy's Unity journey. Lesson 53 of 56.
Challenge
MediumLast step: each level remembers your best time. Keep everything from the earlier lessons. Each level's HUD has a BestText at the top right, and the scene puts it in FinishLine's new bestText field.
In FinishLine (add using TMPro;):
- A
TMP_TextfieldbestTextthat the Inspector sets, and the run's time: afloatthat grows byTime.deltaTimeevery frame. - Each level saves its best under its own PlayerPrefs key:
BestTime_and the level's name, such asBestTime_Level1. - In
Start, show the level's saved best with one decimal, asBest: 12.4 s, orBest: nonewhen it has none yet. - When the player crosses the finish, before the next level loads, save the run's time if the level has no best yet or the run beat it. A slower run leaves the best alone.
Press Play and set a time, then try to beat it, then Check.
Try it yourself
using UnityEngine;
using UnityEngine.SceneManagement;
public class FinishLine : MonoBehaviour
{
void OnTriggerEnter(Collider other)
{
if (other.GetComponent<Player>() == null) return;
Scene level = SceneManager.GetActiveScene();
Debug.Log(level.name + " complete!");
int next = level.buildIndex + 1;
if (next >= SceneManager.sceneCountInBuildSettings)
{
next = 0;
}
SceneManager.LoadScene(next);
}
}
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