using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class AsyncLoad { /// /// 场景名称 /// private string sceneName; /// /// 加载完成后自动进入 /// private bool boolAutomaticEnter; /// /// 加载进度 /// private int loadProgress; /// /// 异步操作 /// private AsyncOperation asyncOperation; /// /// 加载进度 /// public int load_progress { get => loadProgress; } public AsyncOperation AsyncOperation { get => asyncOperation; } public AsyncLoad() { } /// /// /// /// 场景名称 /// 加载完成后是否自动进入 public AsyncLoad(string _sceneName, bool _automaticEnter) { sceneName = _sceneName; boolAutomaticEnter = _automaticEnter; } /// /// 异步加载场景 /// /// /// public IEnumerator AsyncLoadScene(string _scene_name, bool _auto_enter_scene, LoadSceneMode _load_scene_mode = LoadSceneMode.Single) { var _scene = SceneManager.GetSceneByName(_scene_name); if (_scene == null || _scene.isLoaded) { yield break; } yield return new WaitForSeconds(0.1f); int displayProgress = 0; if (!string.IsNullOrEmpty(_scene_name)) { asyncOperation = SceneManager.LoadSceneAsync(_scene_name, _load_scene_mode); asyncOperation.allowSceneActivation = false; while (!asyncOperation.isDone) { int toProgress = (int)asyncOperation.progress * 100; while (displayProgress < toProgress) { ++displayProgress; loadProgress = displayProgress; Debug.Log(load_progress); yield return new WaitForEndOfFrame(); } toProgress = 100; while (displayProgress < toProgress) { ++displayProgress; loadProgress = displayProgress; Debug.Log(load_progress); yield return new WaitForEndOfFrame(); } if (asyncOperation.progress >= 0.89f) { if (_auto_enter_scene) asyncOperation.allowSceneActivation = true; } yield return null; } } } /// /// 异步卸载场景 /// /// /// public IEnumerator AsyncUnloadScene(string _scene_name) { var _scene = SceneManager.GetSceneByName(_scene_name); if (_scene == null || !_scene.isLoaded) yield break; yield return SceneManager.UnloadSceneAsync(_scene_name); } /// /// 进入场景 /// public void EnterScene() { asyncOperation.allowSceneActivation = true; } }