Loading bar in Unity
Objective: Create a loading bar that shows the progress of the level being loaded
A loading bar in Unity is an easy thing to accomplish when you’re loading a new level. I am using a simple script, which I will show in full and some images for the UI.
I have created a new scene called LoadingBar, this is where the code will be. In the main menu of my project I am loading the scene I mentioned LoadingBar and its one job is to show the player the progress of the load.
First thing to do is to set up the canvas so that I can show the player how much of the level has loaded.
Right-click in the scene and create a UI -> Image. This will create a canvas for you add put the image in there. I then rename the image to progress bar and position it where I would like it to appear on screen. I repeated this process for a second UI image but the second one is an overlay.
Click on the first image and change the image type from simple to filled. This allows you to adjust the fill amount in code. I then select horizontal as the fill method. You can choose radial if you like and the same functionality will happen regardless of the method.
I created a C# script called Loading and attached it to the canvas gameobject.
In the script I first expose a field for the image I want to adjust on the screen. I then save the script and drag in the progress bar image into the exposed field in the editor.
I created an IEnumerator and call it in the start method. In the coroutine I create an AsyncOperation which will allow me to run the scene load in the background. This is done with the LoadSceneAsync. The AsyncOperation has its own special methods and I am checking whether the Main scene is loaded.
If the scene is not loaded, I am changing the image fillamount with the progress of the AsyncOperation. Next I am waiting for the next frame before continuing with the while loop. Once the async.isDone returns true then the scene is ready and it is loaded.