我們首先寫(xiě)一個(gè)BuildAssetBundle腳本
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
public class BuildAssetBundle{
/// <summary>
/// 將選中的預(yù)制分別打包
/// </summary>
[MenuItem("build/Create AssetBundles By themselves")]
static void CreateAssetBundleThemelves(){
//獲取要打包的對(duì)象(在Project視圖中)
Object[] selects = Selection.GetFiltered (typeof(Object),SelectionMode.DeepAssets);
//遍歷選中的對(duì)象
foreach(Object obj in selects){
//string outPath=Application.streamingAssetsPath+"/AssetBundle";
//這里建立一個(gè)本地測(cè)試
//注意本地測(cè)試中可以是任意的文件峭判,但是到了移動(dòng)平臺(tái)只能讀取路徑StreamingAssets里面的
//StreamingAssets是只讀路徑次员,不能寫(xiě)入
string targetPath = Application.streamingAssetsPath + "/" + obj.name + ".assetbundle";//文件的后綴名是assetbundle和unity3d都可以
if(BuildPipeline.BuildAssetBundle(obj,null,targetPath,BuildAssetBundleOptions.CollectDependencies)){
Debug.Log(obj.name + "is packed successfully!");
}else{
Debug.Log(obj.name + "is packed failly!");
}
}
//刷新編輯器(不寫(xiě)的話要手動(dòng)刷新,否則打包的資源不能及時(shí)在Project視圖內(nèi)顯示)
AssetDatabase.Refresh ();
}
}
這個(gè)腳本的作用是在Unity主菜單中添加一個(gè)選項(xiàng)卡,來(lái)給我們提供一個(gè)可視化的操作笛园,把我們想要打包的資源打包成一個(gè)AssetsBundle的格式捐韩,該腳本必須放在Assets/Editor的文件夾下
Paste_Image.png
放到下邊以后我們會(huì)發(fā)現(xiàn)在主菜單選項(xiàng)卡中多了一個(gè)Bulid
注意:同時(shí)我們還必須在Assets下新建一個(gè)StreamingAssets文件夾
Paste_Image.png
然后我們選中一個(gè)預(yù)制體或者資源文件,然后點(diǎn)擊Bulid
Paste_Image.png
選中紅箭頭指向的選項(xiàng)我們就會(huì)在SteamingAssets文件夾下發(fā)現(xiàn)我們打包好的文件
Paste_Image.png
然后我們?cè)趯?xiě)一個(gè)腳本把打包的AssetBundle文件給解析出來(lái)
using UnityEngine;
using System.Collections;
public class LoadAssetBundle : MonoBehaviour {
void Start () {
//需要解析的文件名葬燎,該文件必須在StreamingAssets目錄下
StartCoroutine (Load("Sphere"));
}
IEnumerator Load(string path){
string str = "file://" + Application.streamingAssetsPath + "/" + path + ".assetbundle";
WWW w = new WWW (str);
yield return w;
if(w.error==null){
AssetBundle a = w.assetBundle;
GameObject.Instantiate (a.mainAsset);
}
}
// Update is called once per frame
void Update () {
}
}
然后我們把該腳本掛載在攝像機(jī)上邊,我們運(yùn)行看下
Paste_Image.png
Paste_Image.png
然后我們把程序打包成客戶端運(yùn)行
Paste_Image.png
然后我們?cè)诖虬鰜?lái)的文件中修改一個(gè)東西
Paste_Image.png
我們把Cube的名字換成Sphere
Paste_Image.png
然后我們?cè)邳c(diǎn)開(kāi)程序運(yùn)行
Paste_Image.png
然后我們就會(huì)發(fā)現(xiàn)物體變成了Cube缚甩,這樣的好處就是我們?cè)诎l(fā)布一個(gè)程序后有的時(shí)候我們需要修改一些東西谱净,如果我們用的是AssetBundle的時(shí)候,就可以直接在外部修改擅威,沒(méi)有必要在從Unity里去修改了壕探。