How to create a loading scene in Unity
3 min readAug 10, 2021
--
When the GameOver
cut scene is triggered, the UI will show 2 buttons: Restart and Quit
Restart scene
- Create a
UIManager
script with a singleton - Import
UnityEngine.SceneManagement
- Create a method, for example,
public void RestartGame()
- In the method, call
SceneManager.LoadScene(“… scene name …”)
. In this case, the scene’s name isMain1
- Select the Restart button, Add a new OnClick event
- Drag and drop UIManager gameobject into the bottom left slot
- In the drop down list that says No Function, select UIManager/Restart()
Quit
- Create a method, for instance,
public void QuitGame()
- In it, call
Application.Quit()
- Add the method to the button as described for the Restart button
Adding scenes to Build settings
- Go to File/Build settings
- Add the scenes manually (drag and drop) or click on Add Open Scenes
Loading bar
- Create a new scene called LoadingScreen
- Create 2 UI images: Background and Progress_bar
- Add the images. Also you can add an overlay image
- Set the image type to filled and Fill Method to Horizontal
Asynchronous operation
an AsyncOperation in Unity is a coroutine. It has a property float called progress. The documentation says:
This returns how close the operation is to finishing. The operation is finished when the progress float reaches 1.0 and isDone is called
Why is it useful?
When playing videogames, some scenes take some seconds to load, so it is good to show a temporary scene while the new scene finishes loading
Implementation
- Change the scene to load in MainMenu script to LoadingScreen
- Add the scenes to the Build settings, preferably the first one at the top, in descending order (just a good practice)
Code
private Image progressBarprivate void Start() => StartCoroutine(LoadProgressAsync());private IEnumerator LoadProgressAsync()
{
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(gameScene);
while (!asyncLoad.isDone) // while loading isn't finished
{
// progress bar fill amount = operation progress
progressBar.fillAmount = asyncLoad.progress;
yield return new WaitForEndOfFrame();
}
}