Unity3D 使用 WWW 加载场景并显示进度条

Unity3D 加载场景有很多种方式,做一些小的 DEMO 的时候往往是直接使用 Application.LoadLevel 或者 Application.LoadLevelAsync 函数加载场景,具体可查看(http://www.xuanyusong.com/archives/1427),但是这种办法不适合在真正的 Unity3D 开发中,因为前一种需要把所有的场景都打包,这在某些情况下是不现实的,比如开发页游,我们不可能把所有的场景都打包让用户下载,我们需要一个场景一个场景的加载,这时候我们可以使用 WWW 先通过 HTTP 加载场景到本地缓存,然后再使用 Application.LoadLevel 或者 Application.LoadLevelAsync 函数加载场景,使用这种加载方式,不仅不需要 Build Settings -> Add Current 处理加载场景,进度条的显示也更加容易,但是使用这种方式,需要先把场景打包成 unity3d(查看详情) 或者 assetbundle(查看详情) 文件。

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


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

using UnityEngine;
using System.Collections;

public class UseWww : MonoBehaviour 
{
	public UISlider progressBar;
	public UILabel lblStatus;

	private WWW www;
	private string scenePath;

	void Awake()
	{
		this.scenePath = "file:///" + Application.dataPath + "/Assets/MainScene.unity3d";
		// 开始加载场景
		this.StartCoroutine (this.BeginLoader ());
	}

	void Update()
	{
		if (this.www != null && this.progressBar != null && !this.www.isDone) 
		{
			// 更新进度
			this.progressBar.value = this.www.progress;
		}
	}

	private IEnumerator BeginLoader()
	{
		this.lblStatus.text = "场景加载中,请稍候。。。";
		// 加载场景使用 WWW.LoadFromCacheOrDownload,函数,这样加载完成才能使用 Application.LoadLevel 或者 Application.LoadLevelAsync
		this.www = WWW.LoadFromCacheOrDownload (scenePath, Random.Range(0, 100));
		yield return this.www;

		if(!string.IsNullOrEmpty(this.www.error))
		{
			this.lblStatus.text = "场景加载出错!";
		}

		if (this.www.isDone) 
		{
			this.lblStatus.text = "场景正在初始化,请等待。。。";
			Application.LoadLevelAsync("MainScene");
		}
	}
}


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


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




因为前面我封装了一个 WWW 加载管理器(查看详情),我们可以直接拿来使用,我们建立一个新的 C# 脚本,取名 UseWwwLoaderManager.cs,全部代码如下:

using UnityEngine;
using System.Collections.Generic;

public class UseWwwLoaderManager : MonoBehaviour 
{
	public UISlider progressBar;
	public UILabel lblStatus;

	private string scenePath;
	
	void Awake()
	{
		this.scenePath = "file:///" + Application.dataPath + "/Assets/MainScene.unity3d";

		IList<WwwLoaderPath> pathList = new List<WwwLoaderPath> ();
		pathList.Add (new WwwLoaderPath (this.scenePath, Random.Range (0, 100), WwwLoaderTypeEnum.UNITY_3D));

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

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

	private void onLoaderProgress(string path, float currentValue, float totalValue)
	{
		this.progressBar.value = currentValue;
	}

	private void onLoaderComplete()
	{
		this.lblStatus.text = "场景正在初始化,请等待。。。";
		Application.LoadLevelAsync("MainScene");
	}
}

然后我们把原先的脚本从场景移除,挂载这个新的脚本,如图:


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

原文地址:http://www.omuying.com/article/46.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值