1.2两步是文章所提到过的步骤:AssetBundle学习之路(一) ------ 定义/作用/打包流程
打包之后的asset bundle包一般都是放在服务器端,放在APK中会有两个问题:
具体查看链接:https://docs.unity3d.com/Manual/AssetBundles-Native.html
①.AssetBundle.LoadFromMemoryAsync(异步,对应还有同步方法)
②.AssetBundle.LoadFromFile(也有对应的异步方法)
③.WWW.LoadFromCacheOrDownload
如果资源是压缩的,下载的时候会开一个线程,这种下载方式会先判断缓存中有没有,没有才去服务器端下载,使用www时要判断是否有错误
WWW.LoadFromCacheOrDownload可以传CRC参数,从服务器下载asset bundle,由于网络中断或者其他问题有可能导致下载不完整的assetbundle,这时候可以用校验码判断下载的文件是否完整,不完整则重新请求服务器进行下载
④.UnityWebRequest
使用之前首先使用NetBoxs简单的在本地搭建一个服务器
index.html内容为:
UnityWebRequest官方代码:
测试代码:
string uri = @"http://localhost/AssetBundles/cubewall.unity3d";
UnityWebRequest request = UnityWebRequest.GetAssetBundle(uri);
yield return request.Send();
//两种方式可以得到asset bundle对象
//AssetBundle ab = DownloadHandlerAssetBundle.GetContent(request);
AssetBundle ab = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;//request.downloadHandler可以转化为多种对象
//使用里面的资源
GameObject wallPrefab = ab.LoadAsset("CubeWall");
Instantiate(wallPrefab);
本地测试:
string uri = @"file:///E:\Unity Project Workspace\AssetBundleProject\AssetBundles\cubewall.unity3d";//注意3个斜杠,其他代码都一样
如果想要保存到本地,可使用如下代码:
public IEnumerator LoadABRes()
{
request = UnityWebRequest.Get(uri);
Debug.Log(request);
yield return request.SendWebRequest();
CreatFile(Application.persistentDataPath + "/"+ "AB.txt", request.downloadHandler.data, request.downloadHandler.data.Length);
AssetBundle ab=AssetBundle.LoadFromFile(Application.persistentDataPath + "/"+ "AB.txt");
}
void CreatFile(string path, byte[] file, int length)
{
Stream sw;
FileInfo File = new FileInfo(path);
if (!File.Exists)
{
sw = File.Create();
}
else
{
return;
}
sw.Write(file, 0, length);
sw.Close();
sw.Dispose();
}
可以加载图片(Texture)或者预制体(GameObject)或者声音(AudioClip)等等看,同时分为同步和异步两种加载方式