Menu
CoddyTech

Best Time

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

challenge icon

Challenge

Medium

Last 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_Text field bestText that the Inspector sets, and the run's time: a float that grows by Time.deltaTime every frame.
  • Each level saves its best under its own PlayerPrefs key: BestTime_ and the level's name, such as BestTime_Level1.
  • In Start, show the level's saved best with one decimal, as Best: 12.4 s, or Best: none when 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