一、前言
首先,这个需求是这么被创造出来的,我们要在安卓手机上加载超过一个G的资源,正常的Unity的程序员都会立马想到使用Assetbundle进行资源打包和加载,我当然也不例外。于是乎我就吭哧吭哧的熟练的对资源进行打包,然后用异步 AssetBundle.LoadFromFileAsync进行加载,然鹅,居然读取不到资源。为啥?我这个资源是放在手机的SD卡新建的一个文件夹ResourcesData下,谷歌了很多大神的资料都说的是放到Unity的streamingAssets的目录下,比如松哥的文章Unity3D研究院之Android同步方法读取streamingAssets(八十八)可是这个目录是随着APK一起打包的,也就是说我想预先放置Assetbundle资源在安卓手机的指定目录下好像不行。
二、世界上本没有需求想多了就有了
读取Assetbundle的代码如下:
tempPathURL = "file:///storage/emulated/0" + "/ResourcesData/BattlefieldARElecSandbox/Assetbundles/Android/cube";
private IEnumerator LoadAsync()
{
bundleLoadRequest = AssetBundle.LoadFromFileAsync(tempPathURL);
while (!bundleLoadRequest.isDone)
{
yield return bundleLoadRequest;
}
var myLoadedAssetBundle = bundleLoadRequest.assetBundle;
if (myLoadedAssetBundle == null)
{
uiText.text += "Failed LoadAsync:" + tempPathURL;
Debug.Log("Failed to load AssetBundle!");
yield break;
}
var assetLoadRequest = myLoadedAssetBundle.LoadAssetAsync<GameObject>(loadGameObjName);
yield return assetLoadRequest;
GameObject prefab = assetLoadRequest.asset as GameObject;
prefab.transform.position = Vector3.zero;
loadObj = Instantiate(prefab);
myLoadedAssetBundle.Unload(false);
}
在安卓系统的华为mate10和小米2S下试过了都不管用
但是接下来的代码:居然神奇的可以加载出来,资源还是原来的资源,只不过从AssetBundle.LoadFromFileAsync换成了WWW的加载方式,但是这个WWW的加载不能做进度条啊,会在点击加载的时候卡一会儿,因为不是异步加载,我刚开始以为是我打包的姿势不对,然后我又分别打包安卓的Assetbundle的时候三种压缩模式都使用过了,结果还是一样。
// tempPathURL = "file:///storage/emulated/0" + "/ResourcesData/BattlefieldARElecSandbox/Assetbundles/Android/cube";
private IEnumerator LoadWWW2()
{
// tempPathURL = "file:///storage/emulated/0" + "/ResourcesData/hjs";
// tempPathURL = Application.streamingAssetsPath + "/Android/Models/hjs";
using (WWW www = WWW.LoadFromCacheOrDownload(tempPathURL,5))
{
while (!www.isDone)
{
LoadPro = Mathf.RoundToInt(www.progress) * 100 + "%";
Debug.Log(LoadPro);
yield return new WaitForSeconds(0.5f);
}
if (!string.IsNullOrEmpty(www.error))
{
uiText.text += "加载错误:" + www.error;
yield break;
}
else
{
LoadPro = "100%";
AssetBundle bundle = www.assetBundle;
var prefab = bundle.LoadAsset<GameObject>(loadGameObjName);
loadObj = Instantiate(prefab);
loadObj.transform.position = new Vector3(3, 5, 0);
}
}
}
三、总结
我想在手机的SD指定文件夹预先放置Unity的打包好的资源Assetbundle,然后加载的时候只能用WWW的方式,而AssetBundle.LoadFromFileAsync这个方法不管用