對AssetBundleBulit部分程式碼的個人理解
[MenuItem("Tools/AssetsBoundle/SelectBundle")]
//MenuItem是在unity的工具欄中建立一個新的選單欄Tools->AssetBundle->SelectBundle public static void SelectBundle(){
//建立一個字典用於儲存AssetBundleBulid物件,以物件的assetBundleName和assetBundleVariant拼接成字串作為key Dictionary<string,AssetBundleBuild> assets = new Dictionary<string, AssetBundleBuild> (); /*獲取所有的滑鼠選擇的物件,Selection是對滑鼠選擇做出的一些操作,GetFiltered是對滑鼠選擇的物件做出篩選,第一個引數是篩選的型別,第二個引數是篩選的模式,當前是選擇了滑鼠選中的所有資料夾裡面的所有物件*/ Object[] objList = Selection.GetFiltered (typeof(Object), SelectionMode.DeepAssets); //Debug.Log(objList.Length);
//下面的for迴圈是在將選中的物件新增到字典中 for (var i = 0; i < objList.Length; i++) { //Debug.Log (objList[i]); /*獲取該物件的在資原始檔夾中的相對路徑//AssetDatabase是一個對asset進行訪問和操作的密封類,可以通過這個類獲得物件的路徑*/ string path=AssetDatabase.GetAssetPath(objList[i]); Debug.Log (path); //通過路徑返回資源設定好的資源包的名字 string assetName = AssetImporter.GetAtPath (path).assetBundleName; //返回該物件的assetBundleVariant; string variant= AssetImporter.GetAtPath (path).assetBundleVariant; string key = assetName + "." + variant; //Debug.Log (key); if (assets.ContainsKey (key)) { //原基礎更新
/*如果該資源包名字和Variant存在則建立一個AssetBundleBulid物件bulid來儲存該資源包內的AssetBundleBulid物件,bulid有三個屬性assetNames是一個字串陣列用於儲存需要打包的物件的路徑,這裡賦值新增一個路徑之後又重新賦值給該鍵的鍵值*/ AssetBundleBuild build=assets[key]; build.assetNames = AppendChild (build.assetNames, path); assets [key] = build; }else{
/*這裡是在判斷在字典中沒有找到該key,但是key不為null也不是空字串則新建一個bulid並給bulid的三個屬性賦值*/ if (key != null && key != ""&&key.Length>1) { Debug.Log ("456"); AssetBundleBuild build = new AssetBundleBuild (); build.assetBundleName = assetName; build.assetBundleVariant = variant; build.assetNames = new string[]{ path }; assets.Add (key, build); } else {
/*用於打包那些沒有包名的物件這時候key=".",所以將這些沒有包名的物件以它們的型別進行打包*/ key = path.Substring (path.LastIndexOf (".") + 1); Debug.Log (key); if (assets.ContainsKey (key)) { //原基礎更新
/*如果已經建立了該key則新增一個路徑*/ AssetBundleBuild build=assets[key]; build.assetNames = AppendChild (build.assetNames, path); assets [key] = build; }else{ /*如果不存在則新建一個鍵值對*/ AssetBundleBuild build = new AssetBundleBuild (); build.assetBundleName = key; build.assetNames = new string[]{ path }; assets.Add (key, build); }
} } } Debug.Log ("123"); //啟動打包 AssetBundleBuild[] crr=new AssetBundleBuild[assets.Count]; assets.Values.CopyTo (crr,0); Debug.Log (crr[0].assetBundleName);
//這裡進行打包 BuildPipeline.BuildAssetBundles(Application.dataPath+"/AssetsBundle",crr,BuildAssetBundleOptions.ChunkBasedCompression, BuildTarget.StandaloneWindows64); } static string[] AppendChild(string[] arr,string value){ string[] brr = new string[arr.Length + 1]; for (var i = 0; i < arr.Length; i++) { brr [i] = arr [i]; } brr [brr.Length - 1] = value; return brr; } }