New day — new excitement! Another new thing was learned today and I am excited to share it with you.
This article will be focused on creating a Loading Screen to the Stealth Game. First, we need to create a new scene (as the Loading Scene) by clicking File — New Scene (Or Ctrl + N).
Having the background image for the loading screen ready on hand, create a canvas and image in the hiearchy. Drag & Drop the background image.
Set the anchor to stretch on both sides and 0 the distance from all edges — making it to cover the entire screen.
Now, to create the perception that the game is actually loading, we need a progress bar. To give this perception, we create a image (for filling purposes) within the Canvas. Drag & Drop the progress bar image to the source of the image. Then, arrange it according to the red bar.
To easily manipulate the progress bar’s fill, we need to change the image type from the inspector.
To create a better visual, we have added an overlay image just over the progress bar by creating a new image and set its size same as the progress bar.
Now, we are ready to manipulate the loading bar. We already know which component that we need to access from a script to manipulate the fill. However, how are we going to make sure that the bar’s progress will be in sync with game’s actual loading progress?
That’s where Asyncoperation in Unity comes to help. Here’s the definition of it from Unity Manual:
As you can observe, we can check the progress of an operation. The progress property returns a float value in between 0 and 1, just like the fill of our progress bar image.
Using AsyncOperation to load a scene will allow us to load a scene before actually going into it. For detailed information about the progress property, check out Unity manual by clicking here. As can be observed on the link, we need to use CoRoutine. isDone property will be called once the progress reaches to 1.
The logic is not very complicated. In brief, we need to access the filling image’s fill property from the script, update it with the progress of the operation. And open the next scene once the loading is finished. To access the image component of the progress bar, we need to add UnityEngine.UI to the namespaces. Likewise, to be able to use the Scene Management capability, we also need to add UnityEngine.SceneManagement to the namespaces.
Lastly, make sure that you have added the scenes in the Build Settings.
And once we finish our script, we are ready to go. We have simply created an AsyncOperation for the next scene and updated the progress bar as long as it is not finished. Once the isDone property is called, our next scene will be loaded on the screen.
Works like a charm :).