Best Run
Part of the Building Real Games section of Coddy's Unity journey. Lesson 32 of 56.
Challenge
MediumLast step: remember the best run. Keep everything from the earlier lessons. The canvas has a BestText in the top right, and the panel a hidden NewBestText (New best!); the scene puts them in two new fields of GameManager, public TMP_Text bestText; and public GameObject newBestText;. Save the best under the key BestRun, in whole meters:
- In
Start(), load the best (0 for a new player) and show it asBest: 57 m. - In
GameOver(), when the run's whole meters,Mathf.FloorToInt(distance), beat the best, save the new best, show it, and shownewBestText. A shorter run changes nothing.
The best stays through Run again and through quitting the game. Press Play, set a best and try to beat it, then Check.
Try it yourself
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using TMPro;
public enum GameState { Playing, GameOver }
public class GameManager : MonoBehaviour
{
public static GameManager Instance;
public float speed = 10f;
public float speedUp = 0.5f;
public float maxSpeed = 20f;
public TMP_Text distanceText;
public GameObject gameOverPanel;
public Button restartButton;
public GameState state = GameState.Playing;
private float distance;
void Awake()
{
Instance = this;
}
void Start()
{
restartButton.onClick.AddListener(Restart);
}
void Update()
{
if (state != GameState.Playing) return;
speed = Mathf.Min(speed + speedUp * Time.deltaTime, maxSpeed);
distance += speed * Time.deltaTime;
distanceText.text = "Distance: " + Mathf.FloorToInt(distance) + " m";
}
public void GameOver()
{
state = GameState.GameOver;
speed = 0f;
gameOverPanel.SetActive(true);
}
void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
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