AsyncLoadingWithProcessBar.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityEngine.UI;
  4. using UnityEngine.SceneManagement;
  5. namespace ToneTuneToolkit
  6. {
  7. /// <summary>
  8. /// 带进度条的异步场景加载
  9. /// 需要Slider和Text对象
  10. /// 方法 SceneLoading.Instance.LoadingScene(01);
  11. /// </summary>
  12. public class AsyncLoadingWithProcessBar : MonoBehaviour
  13. {
  14. public Slider LoadingSlider;
  15. public Text LoadingText;
  16. public static AsyncLoadingWithProcessBar Instance; // 懒人单例
  17. private void Awake()
  18. {
  19. Instance = this;
  20. }
  21. private void Start()
  22. {
  23. if (LoadingSlider == null || LoadingText == null)
  24. {
  25. TTTDebug.Warning(this.name + "组件缺失");
  26. this.enabled = false;
  27. }
  28. }
  29. /// <summary>
  30. /// 对外接口
  31. /// </summary>
  32. /// <param name="sceneIndex"></param>
  33. public void LoadingScene(int sceneIndex)
  34. {
  35. StartCoroutine(LoadingProcess(sceneIndex));
  36. }
  37. /// <summary>
  38. /// 异步加载场景
  39. /// </summary>
  40. /// <param name="sceneIndex"></param>
  41. /// <returns></returns>
  42. private IEnumerator LoadingProcess(int sceneIndex)
  43. {
  44. float index = 0;
  45. AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(sceneIndex);
  46. asyncOperation.allowSceneActivation = false;
  47. while (index <= 100)
  48. {
  49. index++;
  50. LoadingSlider.value = index / 100;
  51. yield return new WaitForEndOfFrame();
  52. LoadingText.text = index.ToString() + "%";
  53. }
  54. asyncOperation.allowSceneActivation = true; // false会卡住最后10%的进度
  55. }
  56. }
  57. }