Loading Scenes in Unity

Alberto Garcia
2 min readJan 16, 2023

--

To load scenes, the SceneManagement package must be implemented in the script to call the function that loads a scene. The code should look for input in the update method to run the LoadScene method; when to call this and what scene to load depends entirely on the state of the game. For this example, the LoadScene fucntion will work as a restart game button, when the game is over and when the player presses the R key down. The TMPro package is used from Unity 2021 onward.

using UnityEngine.UI;
using TMPro;
using UnityEngine.SceneManagement;

[SerializeField]
private bool _isGameOver;
[SerializeField]
private TMP_Text _restartTxt;

void Start()
{
shipsDestroyed= 0;
_destroyedScore.text = "Destroyed: " + shipsDestroyed;
_gameOverTxt.gameObject.SetActive(false);
_isGameOver= false;
_restartTxt.gameObject.SetActive(false);
}

private void Update()
{
if (Input.GetKeyDown(KeyCode.R) && _isGameOver == true)
{
SceneManager.LoadScene(0);
}
}
public void GameOver()
{
_gameOverTxt.gameObject.SetActive(true);
_isGameOver= true;
_restartTxt.gameObject.SetActive(true);
StartCoroutine(GameOverFlicker());
}

With the Game Over() function called, the _isGameOver bool can now be set to true and with this parameter on, we can now restart our scene when the R key is pressed down. The scene is quick easily called as SceneManager.LoadScene(0) starting with the index on 0 and this being the loop scene for this experience. Scenes may also be loaded by string input through the scene name. Important to always add the required scenes on the build settings.

--

--

Alberto Garcia
Alberto Garcia

No responses yet