- Home /
LoadSceneOnClicks.LoadAsynchronously(int)': not all code paths return a value
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LoadSceneOnClicks : MonoBehaviour {
public Image loadingImage;
public GameObject Loader;
public Slider slider;
public void Loadlevel(int sceneIndex) {
StartCoroutine (LoadAsynchronously (sceneIndex));
}
IEnumerator LoadAsynchronously(int sceneIndex) {
AsyncOperation operation = SceneManager.LoadSceneAsync (sceneIndex);
Loader.SetActive (true);
while (!operation.isDone) {
float progress = Mathf.Clamp01 (operation.progress / .9f);
slider.value = progress;
}
}
Hello everyone please help me why unity is giving me this error LoadSceneOnClicks.LoadAsynchronously(int)': not all code paths return a value
Answer by Daggett110 · Dec 13, 2017 at 06:57 PM
Coroutines are functions that run separately from the main game loop and must yield and return in order to wait. However, doing so will not exit the function. You need to add a "yield return" and an IEnumerator value to your function.
This can be null if that return is meant to wait a frame before returning.
yield return null;
You can also use WaitForSeconds, WaitUntilEndOfFrame, as well as a few other types that return for a set amount of time. In WaitForSeconds, a popular option, you pass a float in to represent the time to wait in seconds. The example below waits for 1 second.
yield return new WaitForSeconds(1f);
In your circumstance, it looks like you want to wait until the async operation is done, updating every frame for what I assume is a loading screen bar. In this instance, I would use yield return null, so your loading bar is updated every frame. The larger amount of time will have a less accurate load bar, but will need to run whatever you want in the loop less. This isn't a hefty set of operations you are running in the loop, so I wouldn't be worries about using yield return null. I recommend this:
while (!operation.isDone) {
float progress = Mathf.Clamp01 (operation.progress / .9f);
slider.value = progress;
yield return null;
}
Hope that helps!