https://blog.csdn.net/qq_15697801/article/details/80003488
打包
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
public class AssetBundleTest : MonoBehaviour
{
[MenuItem("Custom Editor/AssetBundle/Bundle Scene")]
static void CreateSceneALL()
{
//清空一下緩存
Caching.CleanCache();
List<BundleData> strmes = GetSelectionFile(".unity");
Debug.Log(strmes.Count);
if (strmes.Count <= 0)
return;
string Path=string.Empty;
string filepath = PlayerPrefs.GetString("Path");
foreach (var item in strmes)
{
//獲得用戶選擇的路徑的方法,可以打開保存面板(推薦)
if(string.IsNullOrEmpty(Path))
{
if(string.IsNullOrEmpty(filepath))
{
Path = EditorUtility.SaveFilePanel("保存資源", "SS", "" + item.Name, "unity3d");
filepath = Path.Substring(0, Path.LastIndexOf('/'));
}
else
{
Path = filepath+ "/"+item.Name+ ".unity3d";
}
PlayerPrefs.SetString("Path", filepath);
}
//另一種獲得用戶選擇的路徑,默認把打包后的文件放在Assets目錄下
//string Path = Application.dataPath + "/MyScene.unity3d";
//選擇的要保存的對象
string[] levels = {item.LevelsPath };
//打包場景
BuildPipeline.BuildPlayer(levels, Path, BuildTarget.StandaloneWindows64, BuildOptions.BuildAdditionalStreamedScenes);
}
// 刷新,可以直接在Unity工程中看見打包后的文件
AssetDatabase.Refresh();
if(!string.IsNullOrEmpty(filepath))
{
System.Diagnostics.Process.Start(filepath);
Debug.Log("Bundle Success!!!");
}
}
[MenuItem("Custom Editor/AssetBundle/Clear FilePath")]
static public void ClearFilePath()
{
PlayerPrefs.DeleteKey("Path");
Debug.Log("默認地址清除成功!" + PlayerPrefs.GetString("Path"));
}
//得到鼠標選中的文件,只返回文件名及后綴
static public string[] GetSelectionFile()
{
//SelectionMode.Unfiltered 返回整個選擇。
//SelectionMode.TopLevel 僅返回最頂層選擇的變換;其他選擇的子對象將被過濾出。
//SelectionMode.Deep 返回選擇和所有選擇的子變換。
//SelectionMode.ExcludePrefab 從選擇中排除任何預制。
//SelectionMode.Editable 排除任何對象不得修改。
//SelectionMode.Assets 僅返回資源目錄中的資源對象。
//SelectionMode.DeepAssets 如果選擇包含文件夾,也包含所有資源和子目錄。
//SelectionMode.OnlyUserModifiable 僅用戶可修改??
UnityEngine.Object[] arr = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.TopLevel);
string[] str = new string[arr.Length];
for (int i = 0; i < arr.Length; ++i)
{
string s = Application.dataPath.Substring(0, Application.dataPath.LastIndexOf('/')) + "/" + AssetDatabase.GetAssetPath(arr[i]);
Debug.Log(s);
str[i] = s.Substring(s.LastIndexOf('/') + 1, s.Length - s.LastIndexOf('/') - 1);
Debug.Log(str[i]);
}
return str;
}
//得到鼠標選中的文件,驗證后綴返回文件名
static public List<BundleData> GetSelectionFile(string suffix)
{
UnityEngine.Object[] arr = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.TopLevel);
// string[] str = new string[arr.Length];
List<BundleData> liststr = new List<BundleData>();
for (int i = 0; i < arr.Length; ++i)
{
string s = Application.dataPath.Substring(0, Application.dataPath.LastIndexOf('/')) + "/" + AssetDatabase.GetAssetPath(arr[i]);
Debug.Log(s);
var strName = s.Substring(s.LastIndexOf('/') + 1, s.Length - s.LastIndexOf('/') - 1);
if (strName.EndsWith(suffix)) {
// var file = AssetDatabase.GetAssetPath(arr[i]);
// str[i] = GetString(strName, suffix);
// Debug.Log(str[i]);
BundleData strdata = new BundleData();
strdata.AllName = strName;
strdata.Name = GetString(strName, suffix);
strdata.Suffix = suffix;
strdata.FilePath = s;
strdata.LevelsPath= AssetDatabase.GetAssetPath(arr[i]);
liststr.Add(strdata);
}
}
return liststr;
}
///<summary>
/// 截前后字符(串)
///</summary>
///<param name="val">原字符串</param>
///<param name="str">要截掉的字符串</param>
///<param name="all">是否貪婪</param>
///<returns></returns>
private static string GetString(string val, string str, bool all=true)
{
return Regex.Replace(val, @"(^(" + str + ")" + (all ? "*" : "") + "|(" + str + ")" + (all ? "*" : "") + "$)", "");
}
}
public class BundleData{
public string AllName;//名字帶后綴
public string Name;//名字不帶后綴
public string Suffix;//后綴
public string FilePath;//全路徑
public string LevelsPath;//工程內路徑
}
加載
/// <summary>
/// 真的場景加載方式
/// </summary>
/// <returns></returns>
public IEnumerator LoadReallyScene( string path)
{
// path= path.Replace("/","\\");
// !isnewload ? (AppDefine.Bundle_Root_Env + GlobalConfig.Instance.SceneName + ".prefab") : (ModelManager.Instance.GetRelativeDirUrl(RelativeDirEnum.Model) + GlobalConfig.Instance.SceneName + ".prefab");
WWW bundle = new WWW(path);
yield return bundle;
if (bundle.error == null)
{
AssetBundle ab = bundle.assetBundle; //將場景通過AssetBundle方式加載到內存中
AsyncOperation asy = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive); //sceneName不能加后綴,只是場景名稱
yield return asy;
OnSceneLoadEnd(); //執行回調
}
else
{
Debug.LogError(bundle.error);
}
}
