Unity3D技术之加载游戏场景并显示进度条实现详解

来源:互联网 发布:伴奏制作的软件 编辑:程序博客网 时间:2024/04/30 03:04

Unity3D 加载场景有很多种方式,做一些小的 DEMO 的时候往往是直接使用

Application.LoadLevel 或者 Application.LoadLevelAsync 加载场景,,但是这种办法不适合在真正的 Unity3D 开发中,因为前一种需要把所有的场景都打包,这在某些情况下是不现实的,比如开发页游,我们不可能把所有的场景都打包让用户下载,我们需要一个场景一个场景的加载,这时候我们可以使用 WWW 先通过 HTTP 加载场景到本地缓存,然后再使用 Application.LoadLevel 或者 Application.LoadLevelAsync 函数加载场景,使用这种加载方式,不仅不需要 Build Settings -> Add Current 处理加载场景,进度条的显示也更加容易,但是使用这种方式,需要先把场景打包成 unity3d 或者 assetbundle 文件。--来自狗刨学习网

 



先把测试场景搭建好,如图:



 



然后添加一个 C# 脚本,取名 UseWww.cs,全部代码如下:


1. using UnityEngine;

2. using System.Collections;

3. 

4. public class UseWww : MonoBehaviour 

5. {

6. public UISlider progressBar;

7. public UILabel lblStatus;

8. 

9. private WWW www;

10. private string scenePath;

11. 

12. void Awake()

13. {

14. this.scenePath = "file:///" + Application.dataPath + "/Assets/MainScene.unity3d";

15. // 开始加载场景

16. this.StartCoroutine (this.BeginLoader ());

17. }

18. 

19. void Update()

20. {

21. if (this.www != null && this.progressBar != null && !this.www.isDone) 

22. {

23. // 更新进度

24. this.progressBar.value = this.www.progress;

25. }

26. }

27. 

28. private IEnumerator BeginLoader()

29. {

30. this.lblStatus.text = "场景加载中,请稍候。。。";

31. // 加载场景使用 WWW.LoadFromCacheOrDownload,函数,这样加载完成才能使用 Application.LoadLevel 或者 Application.LoadLevelAsync

32. this.www = WWW.LoadFromCacheOrDownload (scenePath, Random.Range(0, 100));

33. yield return this.www;

34. 

35. if(!string.IsNullOrEmpty(this.www.error))

36. {

37. this.lblStatus.text = "场景加载出错!";

38. }

39. 

40. if (this.www.isDone) 

41. {

42. this.lblStatus.text = "场景正在初始化,请等待。。。";

43. Application.LoadLevelAsync("MainScene");

44. }

45. }

46. }

 



然后把这个脚本挂载到游戏场景的一个对象中,设置好相关属性,如图:



 



运行我们的游戏,可以查看进度条的加载情况,当加载完成,自动跳转到下一个场景中,如图:



 



 



 



因为前面我封装了一个 WWW 加载管理器,我们可以直接拿来使用,我们建立一个新的 C# 脚本。

UseWwwLoaderManager.cs,全部代码如下:


1. using UnityEngine;

2. using System.Collections.Generic;

3. 

4. public class UseWwwLoaderManager : MonoBehaviour 

5. {

6. public UISlider progressBar;

7. public UILabel lblStatus;

8. 

9. private string scenePath;

10. 

11. void Awake()

12. {

13. this.scenePath = "file:///" + Application.dataPath + "/Assets/MainScene.unity3d";

14. 

15. IList<WwwLoaderPath> pathList = new List<WwwLoaderPath> ();

16. pathList.Add (new WwwLoaderPath (this.scenePath, Random.Range (0, 100), WwwLoaderTypeEnum.UNITY_3D));

17. 

18. this.lblStatus.text = "场景加载中,请稍候。。。";

19. 

20. WwwLoaderManager.instance.Loader (pathList, onLoaderProgress, onLoaderComplete, "MainScene");

21. }

22. 

23. private void onLoaderProgress(string path, float currentValue, float totalValue)

24. {

25. this.progressBar.value = currentValue;

26. }

27. 

28. private void onLoaderComplete()

29. {

30. this.lblStatus.text = "场景正在初始化,请等待。。。";

31. Application.LoadLevelAsync("MainScene");

32. }

33. }

 


运行,可以看到与上面同样的加载效果。

 

0 0