Menu
CoddyTech

Best Time

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

The last step of the platformer: the player now runs, jumps, rides, respawns, collects gems and crosses into the next level, and each level keeps its best time in PlayerPrefs.

challenge icon

Challenge

Medium

Each level remembers its best time.

  1. In FinishLine, add using TMPro;, [SerializeField] private TMP_Text bestText; and a run time growing by Time.deltaTime.
  2. In Start(), show the best saved under BestTime_ plus the level's name as Best: 12.4 s, or Best: none.
  3. At the finish, before loading, save a first or faster run time.

Press Play, set a time and 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);
    }
}
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

Practice on your own: Unity playground