Loading screens help users know the game is working while content loads. Coroutines let us pause and wait without freezing the game.
0
0
Loading screens with coroutines in Unity
Introduction
When loading a new game level that takes time
When downloading data or assets in the background
When you want to show progress or animation during loading
When you want to keep the game responsive while waiting
When you want to delay actions without blocking the main game
Syntax
Unity
IEnumerator LoadSceneWithLoadingScreen() {
// Show loading screen
loadingScreen.SetActive(true);
// Start loading scene asynchronously
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync("SceneName");
// Wait until loading is done
while (!asyncLoad.isDone) {
// Optionally update progress bar here
yield return null;
}
// Hide loading screen
loadingScreen.SetActive(false);
}Coroutines use IEnumerator and yield return to pause execution.
Use AsyncOperation to load scenes without freezing the game.
Examples
This coroutine waits 2 seconds before continuing.
Unity
IEnumerator SimpleWait() {
Debug.Log("Start waiting");
yield return new WaitForSeconds(2f);
Debug.Log("Waited 2 seconds");
}This coroutine loads a scene and logs progress until done.
Unity
IEnumerator LoadSceneAsync() {
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync("Level1");
while (!asyncLoad.isDone) {
Debug.Log($"Loading progress: {asyncLoad.progress * 100}%");
yield return null;
}
Debug.Log("Loading complete");
}Sample Program
This Unity script shows a loading screen with a progress bar while loading a scene called "SampleScene". It uses a coroutine to update the progress bar smoothly and only hides the loading screen after the scene is ready.
Unity
using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class LoadingScreenController : MonoBehaviour { public GameObject loadingScreen; public Slider progressBar; public void StartLoading() { StartCoroutine(LoadSceneWithLoadingScreen()); } IEnumerator LoadSceneWithLoadingScreen() { loadingScreen.SetActive(true); AsyncOperation asyncLoad = SceneManager.LoadSceneAsync("SampleScene"); asyncLoad.allowSceneActivation = false; while (!asyncLoad.isDone) { float progress = Mathf.Clamp01(asyncLoad.progress / 0.9f); progressBar.value = progress; if (asyncLoad.progress >= 0.9f) { progressBar.value = 1f; asyncLoad.allowSceneActivation = true; } yield return null; } loadingScreen.SetActive(false); } }
OutputSuccess
Important Notes
Always activate and deactivate the loading screen GameObject to show or hide it.
Use asyncLoad.allowSceneActivation = false to control when the scene switches.
Update UI elements like progress bars inside the coroutine for smooth feedback.
Summary
Loading screens keep users informed during long waits.
Coroutines let you wait without freezing the game.
Use AsyncOperation with coroutines to load scenes smoothly.