Unity3D 使用 WWW 加载游戏场景并显示进度条实现详解

2015年03月19日 13:50 0 点赞 0 评论 更新于 2025-11-21 17:45

在 Unity3D 中,加载场景有多种方式。在制作小型 DEMO 时,通常会直接使用 Application.LoadLevel 或者 Application.LoadLevelAsync 函数来加载场景。然而,这种方法并不适用于实际的 Unity3D 开发。因为 Application.LoadLevel 需要将所有场景进行打包,在某些情况下这是不现实的。例如,在开发网页游戏时,不可能让用户下载所有打包好的场景,而是需要逐个加载场景。

此时,可以使用 WWW 先通过 HTTP 将场景加载到本地缓存,然后再使用 Application.LoadLevel 或者 Application.LoadLevelAsync 函数加载场景。采用这种加载方式,不仅无需在 Build Settings -> Add Current 中处理加载场景,而且进度条的显示也更加容易。不过,使用这种方式需要先将场景打包成 unity3d 或者 assetbundle 文件。

实现步骤

1. 搭建测试场景

首先,搭建好测试场景。

2. 添加 C# 脚本

添加一个名为 UseWww.cs 的 C# 脚本,以下是完整代码:

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()
{
// 当 WWW 不为空、进度条不为空且加载未完成时,更新进度条
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");
}
}
}

3. 挂载脚本

将原先的脚本从场景中移除,然后挂载这个新的 UseWww.cs 脚本。

4. 运行游戏

运行游戏,即可看到与上述描述相同的加载效果。

下载地址

点击下载

作者信息

menghao

menghao

共发布了 3994 篇文章