0

Hi i'm going to make a loading screen between scene A and scene B. I have now used Async Operation to bring in Thin B asynchronously. But I can't do that.

I took a log, and all the screens stop until Async Operation's progress reaches 0.9 which I randomly set.

If the progress exceeds 0.9 then everything starts to work.

Why is that? Is it because the capacity of Thin B is very large?

If I can't use Async Operation, how should I make a loading screen? Please help me! I attached my code below.

  IEnumerator Start()
    {
        yield return null;
        StartCoroutine(LoadingProgress(loadSceneName));
    }

    IEnumerator LoadingProgress(string loadSceneName)
    {
        AsyncOperation async = SceneManager.LoadSceneAsync(loadSceneName);
        
        async.allowSceneActivation = false;
       
        float timer = 0.0f;

        while (!async.isDone)
        {
            timer += Time.deltaTime;

            if (async.progress >= 0.9f)
            {
                loadingBar.fillAmount = Mathf.Lerp(loadingBar.fillAmount, 1f, timer);
                if (loadingBar.fillAmount == 1.0f)
                {
                    async.allowSceneActivation = true;
                    yield break;
                }
            }
            else
            {
                loadingBar.fillAmount = Mathf.Lerp(loadingBar.fillAmount, async.progress, timer);

                if (loadingBar.fillAmount >= async.progress)
                {
                    timer = 0f;
                }
            }

            yield return null;
        }
    }
  • **async** is a keyword in `c#` .. it is not Unity specific and thus Unity doesn't change how it behaves. Yes it is asynchronous **if used correctly** ;) **However**, a Coroutine is **NOT** asynchronous. It basically is a temporary `Update` method and indeed by default gets its `MoveNext` call right after `Update` => Coroutines are always executed synchronous in the Unity main thread. The `AsyncOperation` basically is a Coroutine wrapper for an async task ;) – derHugo Jan 29 '21 at 13:30
  • 1
    Note btw **never** compare `float` values using `==`! See e.g. https://stackoverflow.com/questions/3874627/floating-point-comparison-functions-for-c-sharp – derHugo Jan 29 '21 at 13:33
  • since before you reach `0.9` you do `loadingBar.fillAmount = Mathf.Lerp(loadingBar.fillAmount, async.progress, timer); if (loadingBar.fillAmount >= async.progress) { timer = 0f; }` I'd guess the error is somewhere here – derHugo Jan 29 '21 at 13:39
  • @derHugo Thank you for your kind and quick reply! You means Coroutine is excuted in main thread so it is not asynchronous? Then Is it impossible to process tasks asynchronously using corutin because C operates on the main? – wldwkdrn thl Jan 30 '21 at 02:50
  • First of all, I'll try to fix the code as you advised. Thank you. <3 – wldwkdrn thl Jan 30 '21 at 02:50

0 Answers0