Hey everyone, hope ya’ll are well.
So, the documentation for SceneManager.LoadSceneAsync says that it loads the scene asynchronously in the background. I assumed that this meant the current level wouldn’t be affected. But for a short period of time (2 or 3 seconds), the current level does freeze up.
I tried experimenting. I have a simple scene with a Plane, a Slider and a Text object. I have written a script with an IF condition checking if the Space key has been pressed. If it has, another script is enabled. This is the code for the script:
public Slider progBar;
public GameObject continueText;
AsyncOperation ao;
void OnEnabled()
{
StartCoroutine(LoadTheLevel());
}
IEnumerator LoadTheLevel()
{
ao = new AsyncOperation()
ao = SceneManager.LoadSceneAsync(1, LoadSceneMode.Additive); // 1 is the index of the next level.
ao.allowSceneActivation = false;
while(!ao.isDone)
{
progBar.value = ao.progress;
Debug.Log(ao.progress);
if(ao.progress == 0.9f)
{
continueText.SetActive(true); // It is initially disabled
if(Input.GetKeyDown(KeyCode.F))
{
ao.allowSceneActivation = true;
progBar.gameObject.SetActive(false);
continueText.SetActive(false);
}
}
yield return null;
}
progBar.value = ao.progress;
Debug.Log(ao.progress);
}
So, how it works is, when ao.progress reaches 0.9f, the Text object is set to Active. The text says “Press ‘F’ To Continue”. When the player presses F, ao.allowSceneActivation is set to True, allowing the level to show up on the screen.
What confuses me is, if LoadSceneAsync loads the level in the background, why does the game freeze for 2 or 3 seconds while the other level is loading?
I added a Cube to the scene, added a Rigidbody to it, and wrote a small script to move the cube by adding force to it, and also measure it’s velocity. Both tasks are being done in the Update method. So when the game is played, the cube starts moving, and the velocity can be seen changing. Then when is hit the Space key, as expected, the next level starts loading. Again, the same freeze of 2 or 3 seconds happens, and the cube freezes too, but once the game gets out of that freeze, the cube starts moving again, only this time, from a much lower velocity.
If it was just a freeze, how did the velocity go down?