1.建立資源套件:
public class Sript_01 : MonoBehaviour
{
[MenuItem ("自訂資源套件/建立資源套件")]
static void ExecCreateAssetBunldes()
{
//設定儲存資源套件的根路徑
string targetDir = Application.dataPath + "/AssetBundles";
Object[] SelectedAsset = Selection.GetFiltered(typeof (Object),SelectionMode.DeepAssets);
//建立一個目錄,用於儲存資源套件
if(!Eirectory.Exists(targetDir))
{
Directory.CreateDirectory(targetDir);
}
for(int i=0;i<selectedAsset.Length;i++)
{
//產生資源套件的完整路徑
string filepath = targetDir + "/" + SelectedAsset[i].name + ".unity3d";
//根據路徑判斷資源套件檔案是否存在
if(File.Exists(filePath))
{
File.Delete(filePath);
}
//產生新的資源套件檔案
if(BuildPipeline.BuildAssetBundle(SelectedAsset[i],null,filePath,BuildAssetBundleOptions.CollectDependencies))
{
Debug.Log(“資源套件產生成功”);
AssetDatabase.Refresh();
}
else
Debug.Log("資源套件檔案產生失敗");
}
}
}
}
Note: This is an editor class. To use it you have to place your script in
Assets/Editor inside your project folder. Editor classes are in the UnityEditor namespace so for C# scripts you need to add "using UnityEditor;" at the beginning of the script.
2.下載資源套件
IEnumerator loadBundleMat(string name)
{
Material mat;
//資源在原生路徑
WWW date = new WWW("file://" + Application.dataPath + "/AssetBundles/" + name + "./unity3d");
//等待下載完成
yield return date;
//將下載得到的資源強制轉換成材質資源
mat = (Material)date.assetBundle.mainAsset;
//更換為下載的資源
renderer.material = mat;
//釋放資來源物件
date.assetBundle.Unload(false);
}
IEnumerator loadBundleObject (string name)
{
WWW date = new WWW("file://" + Application.dataPath + "AssetBundles/" + name + ".unity3d");
//等待下載完成,並且複製遊戲對象,
yield return Instantiate(date.assetbundle.mainAsset);
//釋放資來源物件
date.assetbundle.Unload(false);
}
注釋: 資源套件下載完成後,資源檔將保持在assetBundle.mainAsset 對象中,接著使用該對象即可。由於連續下載資源套件對象會出錯,所以下載完資源後需要手動釋放對象。