Below is my code to load the next scene in Unity (Asyn). It's working fine. But I need it to wait for a second after loading before showing the scene. How to do it
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LoadingScreenScript : MonoBehaviour
{
[SerializeField]
private Image _progressBar;
// Start is called before the first frame update
void Start()
{
StartCoroutine(LoadAsyncOperatiom());
}
IEnumerator LoadAsyncOperatiom()
{
AsyncOperation gameLevel = SceneManager.LoadSceneAsync(2);
while (gameLevel.progress < 1)
{
_progressBar.fillAmount = gameLevel.progress;
yield return new WaitForEndOfFrame();
}
transition.SetTrigger("Start");
//yield return new WaitForSeconds(transitionTime);
}
}
So by default, Unity enters the scene (and leaves the old one) as soon as the scene is loaded. However, you can change this behaviour using AsyncOperation.allowSceneActivation.
Something to note about this, progress of the scene load will be between [0f-0.9f]
, where 0.9f
represents a fully loaded, but inactive, scene. It will not reach 1.0f
until you set AsyncOperation.allowSceneActivation to true
again, and allow the scene to activate.
Therefore when waiting for the scene to load, you must check against gameLevel.progress < 0.9f
, rather than 1
.
You can change your code to this:
IEnumerator LoadAsyncOperatiom()
{
AsyncOperation gameLevel = SceneManager.LoadSceneAsync(2);
gameLevel.allowSceneActivation = false; // stop the level from activating
while (gameLevel.progress < 0.9f)
{
_progressBar.fillAmount = gameLevel.progress;
yield return new WaitForEndOfFrame();
}
transition.SetTrigger("Start");
yield return new WaitForSeconds(transitionTime);
gameLevel.allowSceneActivation = true; // this will enter the level now
}
And it should work.