读取资源文件:
创建C#脚本名称为RunAssetBundles。
using UnityEngine;
using System.Collections;
public class RunAssetBundles : MonoBehaviour {
//AssetBundle资源路径,不同平台下StreamingAssets的路径是不同的,这里需要注意一下。
public static readonly string PathURL =
#if UNITY_ANDROID//安卓
"jar:file://" + Application.dataPath + "!/assets/";
#elif UNITY_IPHONE//苹果手机
Application.dataPath + "/Raw/";
#elif UNITY_STANDALONE_WIN || UNITY_EDITOR//windows或unity编辑器
"file://" + Application.dataPath + "/StreamingAssets/";
#else
String.Empty;
#endif
void OnGUI()
{
if (GUILayout.Button("Prefab0"))
{
StartCoroutine(LoadMainObj(PathURL + "Prefab0.assetbundle"));
}
if (GUILayout.Button("Prefab1"))
{
StartCoroutine(LoadMainObj(PathURL + "Prefab1.assetbundle"));
}
if (GUILayout.Button("All AssetBundle"))
{
StartCoroutine(LoadAllObj(PathURL + "ALL.assetbundle"));
}
if (GUILayout.Button("Open Scene"))
{
StartCoroutine(LoadAllObj(PathURL + "MyScene.unity3d"));
}
}
private IEnumerator LoadMainObj(string path)
{
//下载类WWW("路径"),bundle只保存在内存中
WWW bundle = new WWW(path);
yield return bundle;
//实例化获取的assetbundle对象
yield return Instantiate(bundle.assetBundle.mainAsset);
// 卸载所有包含在bundle中的内存镜像,若参数为true,在使用中的对象也会被清楚(慎用)
bundle.assetBundle.Unload(false);
}
private IEnumerator LoadAllObj(string path) {
WWW bundle = new WWW(path);
yield return bundle;
Object obj0=bundle.assetBundle.LoadAsset("Prefab0");
Object obj1=bundle.assetBundle.LoadAsset("Prefab1");
yield return Instantiate(obj0);
yield return Instantiate(obj1);
//施放内存--参数:false释放内存、true对象也会被删除
bundle.assetBundle.Unload(false);
}
private IEnumerator LoadScene(string path)
{
var download= WWW. LoadFromCacheOrDownload(PathURL + "AssetbundleScene.unity3d",1);
yield return download;
Application.LoadLevel ("MyScene");
}
}
/*补充:
也可以用AssetBundle.CreatFromFile下载。
Prefab打包资源包选项为
BuildAssetBundleOptions.CollectDependencies|BuildAssetBundleOptions.UncompressedAssetBundle
Scene打包资源包选项为
BuildOptions.UncompressedAssetBundle
路径地址中没有file://
(Android平台中要注意:www方法中路径apk!/assets,CreatFromFile方法中路径apk!asse,叹号后面没有/)
string path=Application.dataPath + "/StreamingAssets/"+"资源名称";
AssetBundle download = AssetBundle.CreateFromFile(path);
yield return download;