理论及参考链接:http://www.xuanyusong.com/archives/2405
using UnityEngine;
using System.Collections;
using UnityEditor;
public class CreateAssetBundle: Editor
{
[MenuItem("GameObject/Create AssetBundles Solo")]
static void CreateAssetBundlesSolo()
{
Object[] selectedAsset = Selection.GetFiltered (typeof(Object), SelectionMode.DeepAssets);
string targetPath = string.Empty;
foreach(Object obj in selectedAsset)
{
targetPath = Application.dataPath + "/StreamingAssets/" + obj.name + ".assetbundle";
if(BuildPipeline.BuildAssetBundle(obj, null, targetPath, BuildAssetBundleOptions.UncompressedAssetBundle | BuildAssetBundleOptions.CollectDependencies))
{
Debug.Log(obj.name + "资源打包成功");
}
else
{
Debug.Log(obj.name + "资源打包失败");
}
}
AssetDatabase.Refresh ();
}
[MenuItem("GameObject/Create AssetBundles All")]
static void CreateAssetBundlesAll()
{
Caching.CleanCache ();
Object[] selectedAsset = Selection.GetFiltered (typeof(Object), SelectionMode.DeepAssets);
string targetPath = Application.dataPath + "/StreamingAssets/All.assetbundle";
foreach(Object obj in selectedAsset)
{
Debug.Log("Create AssetBundles name: " + obj.name);
}
if(selectedAsset.Length > 0)
{
if(BuildPipeline.BuildAssetBundle(null, selectedAsset, targetPath, BuildAssetBundleOptions.UncompressedAssetBundle | BuildAssetBundleOptions.CollectDependencies))
{
Debug.Log("资源打包成功");
AssetDatabase.Refresh ();
}
else
{
Debug.Log("资源打包失败");
}
}
}
}
读取:
using UnityEngine;
using System.Collections;
public class AssetBundle: MonoBehaviour
{
void Start ()
{
//如果预设是一起打包的,则调用下面的代码
StartCoroutine (LoadALLGameObject("file://" + Application.dataPath + "/StreamingAssets/All.assetbundle"));
//如果预设是单独打包的,则调用下面的代码(调用顺序很重要,不支持中文assetbundle)
/*
StartCoroutine (LoadMainGameObject("file://" + Application.dataPath + "/StreamingAssets/Directional light.assetbundle"));
StartCoroutine (LoadMainGameObject("file://" + Application.dataPath + "/StreamingAssets/Terrain.assetbundle"));
StartCoroutine (LoadMainGameObject("file://" + Application.dataPath + "/StreamingAssets/Plane.assetbundle"));
StartCoroutine (LoadMainGameObject("file://" + Application.dataPath + "/StreamingAssets/First Person Controller.assetbundle"));
*/
}
//AssetBundle读取一个资源
private IEnumerator LoadMainGameObject(string path)
{
WWW bundle = WWW.LoadFromCacheOrDownload (path, 1);
yield return bundle;
//加载到游戏中
yield return Instantiate(bundle.assetBundle.mainAsset);
bundle.assetBundle.Unload(false);
}
//AssetBundle读取全部资源
private IEnumerator LoadALLGameObject(string path)
{
WWW bundle = WWW.LoadFromCacheOrDownload (path, 1);
yield return bundle;
//通过Prefab的名称把他们都读取出来
//加载到游戏中(调用顺序很重要,支持中文名预设)
yield return Instantiate(bundle.assetBundle.Load("Directional light"));
yield return Instantiate(bundle.assetBundle.Load("Terrain"));
yield return Instantiate(bundle.assetBundle.Load("Plane"));
yield return Instantiate(bundle.assetBundle.Load("First Person Controller"));
bundle.assetBundle.Unload(false);
}
}