讨论完了一个AssetBundle的简单用法,下面我们介绍稍微复杂一点的用法,仍然是基于android平台。对于一个游戏的资源来讲,我们会考虑下载一次之后就不用再次下载了,只要从本地加载就可以了。要达到这个目的,我们可以将操作分为两个步骤,第一个步骤是将文件下载到本地,第二个步骤是将文件从本地加载为AssetBundle类型的资源。下面我们仍然以一个简单的例子来进行说明。
1、承接上一篇文章的步骤,我们在本章仍然以胶
囊体的AssetBundle作为例子,首先创建一个AssetBundle放到服务器上。具体请参照上一篇文章的步骤1-6。

2、编写下载脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.Networking;
using UnityEngine.UI;
public class Downdload : MonoBehaviour
{
public AudioSource audioSource;
string urlPath;//资源网络路径
string file_SaveUrl;//资源保路径
FileInfo file;
public static Downdload instance;
private bool p = true;
private bool down;
private float t;
private float time;
private string s="load";//下载按钮显示内容
private void Awake()
{
instance = this;
}
private void Start()
{
time = 3;
t = 0;
}
void OnGUI(){
if(GUILayout.Button(s,GUILayout.Width(800),GUILayout.Height(300))){//下载测试按钮
Downdload.instance.play ();
}
if (GUILayout.Button (MyBehaviour.show,GUILayout.Width(800),GUILayout.Height(300))) {//加载测试按钮
MyBehaviour.instance.AssetLoadFromFile2();
}
}
public void play()
{
urlPath = "http://app.snaildada.com/testweb/AssetBundles/cab";
file_SaveUrl=Application.persistentDataPath+"\\cab.unity3d";//保存的本地路径 记得加上文件后缀名
s = file_SaveUrl;
file = new FileInfo(file_SaveUrl);
DirectoryInfo mydir = new DirectoryInfo(file_SaveUrl);
if (File.Exists(file_SaveUrl))//判断一下本地是否有了该文件 如果有就不需下载
{
s = "local have :"+file_SaveUrl;
}
else
{
StartCoroutine(DownFile(urlPath));
}
}
IEnumerator DownFile(string url)
{
WWW www = new WWW(url);
down = false;
yield return www;
down = true;
if (www.isDone)
{
byte[] bytes = www.bytes;
CreatFile(bytes);
s="download ok:"+file_SaveUrl;
}
}
void CreatFile(byte[] bytes)
{
Stream stream;
stream = file.Create();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
stream.Dispose();
}
}
3、编写加载脚本
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using System.IO;
public class MyBehaviour : MonoBehaviour
{
public static MyBehaviour instance;
public static string show="create";
void Start()
{
instance = this;
}
public void AssetLoadFromFile2() {//从byte流读取
string path=Application.persistentDataPath+"\\cab.unity3d";
FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
fileStream.Seek(0, SeekOrigin.Begin);
byte[] bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, (int)fileStream.Length);
fileStream.Close();
fileStream.Dispose();
fileStream = null;
show = "" + bytes.Length;
AssetBundle ab = AssetBundle.LoadFromMemory (bytes);
GameObject cubeWall = ab.LoadAsset<GameObject>("Capsule");//获取prefab
show="bytes ok:"+path;
Instantiate(cubeWall, Vector3.zero, Quaternion.identity);//实例化prefab
}
}
4、将上面两个脚本挂到场景中的对象上,执行程序:

5、点击第一个按钮,加载资源,加载完成后会有“download ok”提示如下,(如果再次下载,则会出现以“local have”开头的提示):

6、点击第二个按钮,加载资源并在场景中生成一个对象:

在android手机上实测可用,ok
本文详细介绍了在Unity中使用AssetBundle进行资源下载和本地加载的方法。通过编写下载脚本和加载脚本,实现资源的一次下载多次使用,提高了游戏资源管理的效率。

被折叠的 条评论
为什么被折叠?



