using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; /******************************************************************************** *Create By CG *Function 异步场景加载控制(有界面显示) *********************************************************************************/ namespace CG.UTility { public class LoadScenesAsync : MonoBehaviour { private bool _isLoadScene;//是否加载场景 private AsyncOperation _async; private int _toProgress = 0;//读取场景进度 private int _nowProgress = 0;//当前场景返回进度 [SerializeField] private Slider _slider=null;//进度条 [SerializeField] private Text _sliderTxt=null;//显示百分比 private System.Action _loadedCall = null; private void Update() { if (_isLoadScene) { if (_async == null) return; if (_async.progress < 0.9f) { _toProgress = (int)_async.progress * 100; } else { _toProgress = 100; } if (_nowProgress < _toProgress) { _nowProgress++; } _slider.value = _nowProgress / 100.0f; _sliderTxt.text = _slider.value * 100 + "%"; if (_nowProgress == 100) { _isLoadScene = false; _async.allowSceneActivation = true; _loadedCall?.Invoke(); } } } /// /// 加载场景主方法 /// /// public void LoadSceneAsync(string sceneName, System.Action LoadedCall) { _loadedCall = LoadedCall; gameObject.SetActive(true); _toProgress = 0; _nowProgress = 0; _isLoadScene = true; StartCoroutine("LoadScene", sceneName); } private IEnumerator LoadScene(string sceneName) { yield return new WaitForEndOfFrame();//加上这句可以先让加载画面显示 _async = SceneManager.LoadSceneAsync(sceneName); _async.allowSceneActivation = false; yield return _async; Destroy(gameObject); } } }