Unity3d之AssetBundle打包与服务器资源下载

1.AssetBundle资源打包
AssetBundle资源打包其实就是把资源文件压缩起来,使其占用的空间更少。空间位置是有限的,而我们的时间相对来说更多一些:)在这里要用到编辑器扩展的知识。首先要建立一个名为"Editor"的文件夹,在里面编写用于扩展的脚本。同时需要引入命名空间UnityEditor。
[MenuItem("AssetBundle/打包")
static void BuildAssetBundle(){                        //静态, 无返回值
string path = Application.dataPath + "/AssetBundles"; //dataPath:Contains the path to the game data 
                                                      //folder
BuildPipeline.BuildAssetBundle(path, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindow64);

}
这里的BuildAssetBundleOptions介绍三种:
None:打包后的资源体积最小(意味着所用的时间也越长)
UncompressedAssetBundle:不使用压缩方式,打包后的体积最大,但是加载速度最快
ChunkBasedCompression:打包后的AssetBundle体积和加载速度介于二者之间

2.在本地从web服务器端下载所有的AssetBundle文件时,我们需要有它们的文件地址(每一个地址对应一个AssetBundle文件)。首先我们要下载“目录”AssetBundle文件,再通过它们来获取其他AssetBundle的文件地址。

下面是与“网络请求”相关的API,首先要引入相应的命名空间:using UnityEngine.Netwroking;
//创建一个web请求,用于下载AssetBundle
UnityWebRequest request = UnityWebRequest.GetAssetBundle(url);
//发送web请求
yield return request.Send();
//从请求中获取内容,返回一个AssetBundle类型的数据(即为“目录”AssetBundle)
AssetBundle ab = DownloadHandlerAssetBundle.GetContent(request);
//从此文件中获取manifest数据
AssetBundleManifest manifest = ab.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
//获取manifest文件中所有的AssetBundle名称
string[] assets = manifest.GetAllAssetBundles();

服务器端下载所有文件:
    //通过获取到的AssetBundle对象得到内部所有资源的名称        
    string[] names = ab.GetAllAssetNames();
    //截取路径地址中的文件名,且无后缀。需引入System.IO命名空间
    Path.GetFileNameWithoutExtension(path);

3.不过以上方法只能够从服务器端下载资源,并不能够将AssetBundle资源下载到StreamingAssets。若是每次打开游戏都要从服务器端下载,既浪费流量又浪费时间。那我们就要想办法把下载的资源缓存起来。这里介绍以下API:
//创建一个WWW类的web请求,参数为AssetBundle的下载地址
WWW www = new WWW(url);
//将对象作为数据返回,此对象就是请求(下载)来的数据
yield return www;
//这里引入一个属性,用于表示下载状态是否完毕。当下载完毕时,可以把此对象储存到本地
www.isDone

4.存储
用IO技术存储资源,需要引入IO。引入明明空间System.IO。在用读写流的时候,数据先被读入内存中,然后再写入文件中。
//创建一个FileInfo对象
FileInfo fileInfo = new FileInfo(文件完整路径+名称);
//创建一个文件流对象
FileSream fs = fileInfo.Creat();
//通过该对象往此文件写入信息
fs.Write(字节数组, 开始位置, 数据长度);
//接下来三行代码为文件写入存储硬盘,关闭文件流对象,销毁文件对象。依次执行,不要写错顺序。
fs.Flush();
fs.Close();
fs.Dispose();

这里写图片描述
www.bytes:Return the contents of the fetched web page as a byte array
这里写图片描述
fs.Write();中文件的开始位置一般填0

猜你喜欢

转载自blog.csdn.net/LightInDarkness/article/details/79250215