一、环境
基于Unity2018.2
二、思路
1.使用UnityWebRequest.Get方法去获取AB包
2.在协程中返回UnityWebRequest实例对象的SendWebRequest方法返回值
3.当UnityWebRequest实例对象IsDone的时候取得数据流,进行文件写入
三、核心代码
/// <summary>
/// 保存AssetBundle文件到本地
/// </summary>
IEnumerator SaveAssetBundle(string path)
{
while (!Caching.ready)
yield return null;
using (UnityWebRequest uwr = UnityWebRequest.Get(path))//路径名(例如"file://worksapce/cube.assetbundle")
{
yield return uwr.SendWebRequest();
if (uwr.error != null)
throw new Exception("www download had an error" + uwr.error);
LoadProgress = uwr.downloadProgress;
if (uwr.isDone)
{
byte[] results = uwr.downloadHandler.data;
Bundle = AssetBundle.LoadFromMemory(uwr.downloadHandler.data);
Bytes = uwr.downloadHandler.data;
FileInfo fileInfo = new FileInfo(Application.streamingAssetsPath + "/" + Bundle.name);
FileStream fs = fileInfo.Create();
//fs.Write(字节数组, 开始位置, 数据长度);
fs.Write(uwr.downloadHandler.data, 0, uwr.downloadHandler.data.Length);
fs.Flush(); //文件写入存储到硬盘
fs.Close(); //关闭文件流对象
fs.Dispose(); //销毁文件对象
}
}
}