当前位置:   article > 正文

Unity中实现异步加载场景_unity 异步批量加载场景

unity 异步批量加载场景

当使用异步加载场景时,progress的值永远都不会达到1,当到达0.9时直接跳转场景,使进度条看上去很不平滑,可以通过以下的写法完善异步加载的进度条

一:第一种方法

将此脚本挂载到进度条身上

  1. using UnityEngine.UI;
  2. using UnityEngine;
  3. using UnityEngine.SceneManagement;
  4. using System.Collections;
  5. public class LoadGame : MonoBehaviour
  6. {
  7. private Slider loadingSlider;//加载进度条
  8. private void Start()
  9. {
  10. loadingSlider = GetComponent<Slider>();
  11. StartCoroutine(LoadScene());
  12. }
  13. //加载场景
  14. private IEnumerator LoadScene()
  15. {
  16. int displayProgress = 0;
  17. int toProgress = 0;
  18. AsyncOperation op = SceneManager.LoadSceneAsync(2);
  19. op.allowSceneActivation = false;
  20. while (op.progress < 0.9f)
  21. {
  22. toProgress = (int)op.progress * 100;
  23. while (displayProgress < toProgress)
  24. {
  25. ++displayProgress;
  26. SetLoadingPercentage(displayProgress);
  27. yield return new WaitForEndOfFrame();
  28. }
  29. }
  30. toProgress = 100;
  31. while (displayProgress < toProgress)
  32. {
  33. ++displayProgress;
  34. SetLoadingPercentage(displayProgress);
  35. yield return new WaitForEndOfFrame();
  36. }
  37. op.allowSceneActivation = true;
  38. }
  39. //设置进度条百分比
  40. private void SetLoadingPercentage(float v)
  41. {
  42. loadingSlider.value = v / 100;
  43. }
  44. }

二:第二种方法

将此脚本挂载到进度条身上

  1. using UnityEngine.UI;
  2. using UnityEngine;
  3. using UnityEngine.SceneManagement;
  4. using System.Collections;
  5. public class LoadGame : MonoBehaviour
  6. {
  7. private Slider loadingSlider;//加载进度条
  8. private AsyncOperation async;//异步加载的返回值
  9. private int nowprocess = 0;//当前进度
  10. void Start()
  11. {
  12. loadingSlider = GetComponent<Slider>();
  13. StartCoroutine(LoadScene());
  14. }
  15. //加载场景
  16. IEnumerator LoadScene()
  17. {
  18. async = SceneManager.LoadSceneAsync(2);
  19. async.allowSceneActivation = false;//设置加载完成后不能自动跳转场景
  20. yield return async;
  21. }
  22. void Update()
  23. {
  24. if (async == null)
  25. {
  26. return;
  27. }
  28. int toProcess;//进度条需要到达的进度值
  29. if (async.progress < 0.9f)
  30. {
  31. toProcess = (int)(async.progress * 100);
  32. }
  33. else
  34. {
  35. toProcess = 100;
  36. }
  37. if (nowprocess < toProcess)
  38. {
  39. nowprocess++;
  40. }
  41. // 设置滑动条的value
  42. loadingSlider.value = nowprocess / 100f;
  43. //如果滑动条的值等于100,说明加载完毕
  44. if (nowprocess == 100)
  45. {
  46. async.allowSceneActivation = true;
  47. }
  48. }
  49. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/114214
推荐阅读
相关标签
  

闽ICP备14008679号