AsyncLoadingWithProcessBar.cs 1.6 KB

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