Breakout Clone 4: Transitioning Levels

Alright, time to add another level and transition to it when all blocks on the current level are destroyed! To do this we're going to create a long-lived object named GameSession. Eventually we'll also use this object to track the players score, but for now it will only be responsible for scene transitions.

To ensure that there is only ever one GameSession object active at any given time, we'll employ a pattern I used in a SkillShare course that I took.

public class GameSession : MonoBehaviour
{

  void Awake() {
    int numGameSessions = FindObjectsOfType<GameSession>().Length;

    if(numGameSessions > 1) {
      // destroy this object if there is already a GameSession active.
      Destroy(gameObject);
    } else {
      // Tell Unity to not destroy this object when unloading the current scene.
      DontDestroyOnLoad(gameObject);
    }
  }

  public void LoadNextLevel() {
    int nextSceneIndex = SceneManager.GetActiveScene().buildIndex + 1;
    SceneManager.LoadScene(nextSceneIndex);
  }
}

In my DestroyBlockIfDead method, I'll check to see if there are any other blocks remaining, and if not, I'll call the LoadNextLevel method on our GameSession.

  private void DestroyBlockIfDead() {
    if (currentHealth > 0) {
      return;
    }

    GameSession gameSession = FindObjectOfType<GameSession>();

    int numberOfBlocksRemaining = GameObject.FindGameObjectsWithTag("Block").Length - 1;
    if(numberOfBlocksRemaining == 0) {
      gameSession.LoadNextLevel();
    }

    Destroy(gameObject);
  }

The process for creating the next level is fairly simple. I created "prefabs" of the paddle, ball, block, and walls objects, created a new scene, (I just duplicated the current one,) and added some more blocks. Finally I opened the build settings in Unity to make sure the current scene was part of the build.

And voila! Multiple levels.

Published: 2023-02-18