天天看點

同時加載多個場景需要等待一幀

using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using Zero.Singleton;

namespace Zero.SceneLoader
{
    public class SceneLoader : MonoSingleton<SceneLoader>
    {
        private string _loadScene;

        public void Load(string sceneName)
        {
            _loadScene = sceneName;

            // 加載'Loading'場景
            SceneManager.LoadScene("Loading");
            // 異步加載目标場景
            StartCoroutine(LoadSceneCoroutine(_loadScene));
        }

        private IEnumerator LoadSceneCoroutine(string sceneName)
        {
            // 關鍵: 必須等待一幀, 否則會立刻加載目标場景 
            yield return null;

            var asyncOperation = SceneManager.LoadSceneAsync(sceneName);
            asyncOperation.allowSceneActivation = false;
            yield return new WaitUntil(() => asyncOperation.progress >= 0.9f);
            asyncOperation.allowSceneActivation = true;
        }
    }
}