Unity异步加载场景与加载进度条

异步加载场景分为A、B、C三个场景

A场景是开始场景;B场景是加载场景(进度条加载显示);C场景是目标场景

在A场景中添加一个按钮,触发函数:

[csharp]  view plain  copy
  1. //异步加载新场景  
  2. public void LoadNewScene()  
  3. {  
  4.     //保存需要加载的目标场景  
  5.     Globe.nextSceneName = "Scene";  
  6.   
  7.     SceneManager.LoadScene("Loading");        
  8. }  


在B场景中添加一个脚本,挂载到Camera下

[csharp]  view plain  copy
  1. using UnityEngine;  
  2. using System.Collections;  
  3. using UnityEngine.UI;  
  4. using UnityEngine.SceneManagement;  
  5.   
  6. public class Globe  
  7. {  
  8.     public static string nextSceneName;  
  9. }  
  10.   
  11. public class AsyncLoadScene : MonoBehaviour  
  12. {  
  13.     public Slider loadingSlider;  
  14.   
  15.     public Text loadingText;  
  16.   
  17.     private float loadingSpeed = 1;  
  18.   
  19.     private float targetValue;  
  20.   
  21.     private AsyncOperation operation;  
  22.   
  23.     // Use this for initialization  
  24.     void Start ()  
  25.     {  
  26.         loadingSlider.value = 0.0f;  
  27.   
  28.         if (SceneManager.GetActiveScene().name == "Loading")  
  29.         {  
  30.             //启动协程  
  31.             StartCoroutine(AsyncLoading());  
  32.         }  
  33.     }  
  34.   
  35.     IEnumerator AsyncLoading()  
  36.     {  
  37.         operation = SceneManager.LoadSceneAsync(Globe.nextSceneName);  
  38.         //阻止当加载完成自动切换  
  39.         operation.allowSceneActivation = false;  
  40.   
  41.         yield return operation;  
  42.     }  
  43.       
  44.     // Update is called once per frame  
  45.     void Update ()  
  46.     {  
  47.         targetValue = operation.progress;  
  48.   
  49.         if (operation.progress >= 0.9f)  
  50.         {  
  51.             //operation.progress的值最大为0.9  
  52.             targetValue = 1.0f;  
  53.         }  
  54.   
  55.         if (targetValue != loadingSlider.value)  
  56.         {  
  57.             //插值运算  
  58.             loadingSlider.value = Mathf.Lerp(loadingSlider.value, targetValue, Time.deltaTime * loadingSpeed);  
  59.             if (Mathf.Abs(loadingSlider.value - targetValue) < 0.01f)  
  60.             {  
  61.                 loadingSlider.value = targetValue;  
  62.             }  
  63.         }  
  64.       
  65.         loadingText.text = ((int)(loadingSlider.value * 100)).ToString() + "%";  
  66.   
  67.         if ((int)(loadingSlider.value * 100) == 100)  
  68.         {  
  69.             //允许异步加载完毕后自动切换场景  
  70.             operation.allowSceneActivation = true;  
  71.         }  
  72.     }  
  73. }  


这里需要注意的是使用AsyncOperation.allowSceneActivation属性来对异步加载的场景进行控制

为true时,异步加载完毕后将自动切换到C场景

最后附上效果图




猜你喜欢

转载自blog.csdn.net/qq_36848370/article/details/79915827