Unity3D技术之加载游戏场景
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Unity3D技术之加载游戏场景
Unity3D加载场景有很多种方式,做一些小的 DEMO 的时候往往是直接使用
Application.LoadLevel 或者 Application.LoadLevelAsync 加载场景,,但是这种办法不适合在真正的 Unity3D 开发中,因为前一种需要把所有的场景都打包,这在某些情况下是不现实的,比如开发页游,我们不可能把所有的场景都打包让用户下载,我们需要一个场景一个场景的加载,这时候我们可以使用 WWW 先通过 HTTP 加载场景到本地缓存,然后再使用 Application.LoadLevel 或者 Application.LoadLevelAsync 函数加载场景,使用这种加载方式,不仅不需要 Build Settings -> Add Current 处理加载场景,进度条的显示也更加容易,但是使用这种方式,需要先把场景打包成 unity3d 或者assetbundle 文件,文章出处【狗刨学习网】。
先把测试场景搭建好,如图:
然后添加一个 C# 脚本,取名 UseWww.cs,全部代码如下:
ing UnityEngine;
ing 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;
ing 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
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.}
运行,可以看到与上面同样的加载效果。