Consider this Unity coroutine that simulates a loading screen progress. What will be printed in the console?
using System.Collections; using UnityEngine; public class Loader : MonoBehaviour { IEnumerator StartLoading() { int progress = 0; while (progress < 100) { progress += 20; Debug.Log($"Loading: {progress}%"); yield return new WaitForSeconds(0.5f); } Debug.Log("Loading Complete!"); } void Start() { StartCoroutine(StartLoading()); } }
Check how the progress variable changes inside the loop and when the final message is printed.
The coroutine increases progress by 20 each loop until it reaches 100. It prints each progress step and finally prints "Loading Complete!" after the loop.
Choose the correct statement about using coroutines for loading screens in Unity.
Think about how coroutines help keep the game responsive during loading.
Coroutines run on the main thread but pause execution to allow other code to run, enabling asynchronous behavior without freezing the game.
Examine the coroutine below. It is supposed to simulate loading progress but never prints "Loading Complete!". What is the cause?
IEnumerator LoadScene()
{
float progress = 0f;
while (progress <= 1f)
{
progress += 0.2f;
Debug.Log($"Progress: {progress * 100}%");
yield return new WaitForSeconds(0.5f);
}
Debug.Log("Loading Complete!");
}Consider how floating point numbers behave when incremented repeatedly.
Floating point precision can cause progress to never exactly exceed 1.0, so the loop condition remains true indefinitely.
Identify the correct syntax for a Unity coroutine that waits 1 second and then prints "Done Loading".
Remember the correct way to yield a WaitForSeconds in a coroutine.
The correct syntax uses 'yield return new WaitForSeconds(1);' inside an IEnumerator method.
You want to update a UI loading bar fill amount smoothly from 0 to 1 over 3 seconds using a coroutine. Which code snippet achieves this?
using UnityEngine; using UnityEngine.UI; public class LoadingBar : MonoBehaviour { public Image loadingBar; IEnumerator FillBar() { float elapsed = 0f; while (elapsed < 3f) { loadingBar.fillAmount = elapsed / 3f; elapsed += Time.deltaTime; yield return null; } loadingBar.fillAmount = 1f; } }
Think about the condition to stop the loop and how to calculate fill amount as a fraction of elapsed time.
Option B correctly updates fillAmount from 0 to 1 over 3 seconds using elapsed/3f and stops when elapsed exceeds 3 seconds.