Load all scenes during splash screen

2019-02-14 23:33发布

问题:

I have a multiple scenes in my mobile 2D unity game, I want to load all my scenes in splash screen, so that the scene passing would be smooth. How can I do this ?

If I do this, do I need to change "Application.LoadScene()" method, and what method can I use ?

回答1:

do I need to change "Application.LoadScene()" method, and what method can I use ?

You need to use SceneManager.LoadSceneAsync if you don't want this to block Unity while loading so many scenes. By using SceneManager.LoadSceneAsync, you will be able to show the loading status.

I want to load all my scenes in splash screen

Create a scene and make sure that this scene loads before any other scene. From there you can loop from 0 to the max index of your scene. You can use SceneManager.GetSceneByBuildIndex to retrieve the Scene from index then SceneManager.SetActiveScene to activate the scene you just retrieved.

List<AsyncOperation> allScenes = new List<AsyncOperation>();
const int sceneMax = 5;
bool doneLoadingScenes = false;

void Startf()
{
    StartCoroutine(loadAllScene());
}

IEnumerator loadAllScene()
{
    //Loop through all scene index
    for (int i = 0; i < sceneMax; i++)
    {
        AsyncOperation scene = SceneManager.LoadSceneAsync(i, LoadSceneMode.Additive);
        scene.allowSceneActivation = false;

        //Add to List so that we don't lose the reference
        allScenes.Add(scene);

        //Wait until we are done loading the scene
        while (scene.progress < 0.9f)
        {
            Debug.Log("Loading scene #:" + i + " [][] Progress: " + scene.progress);
            yield return null;
        }

        //Laod the next one in the loop
    }

    doneLoadingScenes = true;
    OnFinishedLoadingAllScene();
}

void enableScene(int index)
{
    //Activate the Scene
    allScenes[index].allowSceneActivation = true;
    SceneManager.SetActiveScene(SceneManager.GetSceneByBuildIndex(index));
}

void OnFinishedLoadingAllScene()
{
    Debug.Log("Done Loading All Scenes");
}

You can the enableScene(int index) to enable the scene. Note that only one scene can be loaded at a time and you must activate them in the order you loaded them and finally, do not lose the reference of AsyncOperation. This is why I stored them in a List.

If you run into problems, try to remove allScenes[index].allowSceneActivation = true; and scene.allowSceneActivation = false;. I've seen these causing problems sometimes.