Hi,
I try to optimize the scene loading speed by pre loading the next scene(Scene1), and set the asyncOperation.allowSceneActivation = false
, until the actual scene change happened. But player has a change will go to other scene(Scene2) instead of pre loaded Scene1.
Here’s the problem:
If the player choose to go Scene2, then Scene1 will become active first for a split second and then go to Scene2. even the scripts in Scene1 runs their Awake functions.
I tried to Unload Scene1 before going to Scene2, but problem still there, I don’t know this behavior is intended or a bug?
Here’s my code:
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
public class TestSceneLoading : MonoBehaviour
{
private static void OnSceneChange(Scene oldScene, Scene newScene)
{
Debug.Log($"oldScene:{oldScene.path}");
Debug.Log($"newScene:{newScene.path}");
}
private void Awake()
{
SceneManager.activeSceneChanged += OnSceneChange;
}
private IEnumerator Start()
{
Debug.Log("start loading Scene1");
var ao = SceneManager.LoadSceneAsync("Scene1");
ao.allowSceneActivation = false;
while (ao.progress < .9f)
{
yield return null;
}
Debug.Log("Scene1 loaded");
yield return new WaitForSeconds(2);
Debug.Log("prepare to unload Scene1");
ao = SceneManager.UnloadSceneAsync("Scene1",UnloadSceneOptions.UnloadAllEmbeddedSceneObjects);
yield return ao;
Debug.Log("Scene1 unloaded, prepare to go Scene2");
yield return new WaitForSeconds(2);
Debug.Log("start going to Scene2");
SceneManager.LoadScene("Scene2");
}
}
and result log is:
Red square shows that Unity went to Scene1 first.
Orange square shows that Scripts in Scene1 executed their Awake function.