前言:
一般用于ui资源打包和加载,代码比较简单没什么好说的,直接上代码。
打包代码:
[MenuItem("Assets/打包指定的预设")]
public static void BuildAsset() {
var selectObject = Selection.activeObject;
if (selectObject != null) {
if (selectObject is GameObject go) {
try {
EditorUtility.DisplayProgressBar("打包资源", go.name, 1.0f);
AssetBundleBuild build = new AssetBundleBuild();
var path = Application.streamingAssetsPath + "/assetbundle";
if (!Directory.Exists(path)) {
Directory.CreateDirectory(path);
}
build.assetBundleName = go.name;
build.assetNames = new string[] { AssetDatabase.GetAssetPath(selectObject) };
AssetBundleManifest manifest = BuildPipeline.BuildAssetBundles(path,
new AssetBundleBuild[] { build },
BuildAssetBundleOptions.ChunkBasedCompression, BuildTarget.StandaloneWindows64);
File.Delete(path + "/" + go.name + ".manifest");
AssetDatabase.Refresh();
}
catch (Exception e) {
Debug.Log($"打包资源:{go.name}失败,Error:{e.Message}");
}
EditorUtility.ClearProgressBar();
}
}
//string inputPath = EditorUtility.OpenFolderPanel("选择编译文件夹",
// UnityEngine.Application.dataPath, "HostScripts");
//if (string.IsNullOrEmpty(inputPath)) {
// EditorUtility.DisplayDialog("错误", "必须选择文件夹才能进行编译", "确定");
//}
}
加载代码:
public void LoadUIformAB<T>(string path, string assetName, Action<T> callBack) where T : UnityEngine.Object {
AssetBundle ab = null;
if (abUIMap.TryGetValue(path, out ab)) {
try {
T asset = (T)GameObject.Instantiate(ab.LoadAsset(assetName));
callBack?.Invoke(asset);
}
catch (Exception e) {
McLogger.Error("UI", nameof(UISetting), $"加载UIab包报错{e.Message}---->{e.StackTrace}");
callBack?.Invoke(null);
}
}
else {
if (File.Exists(path)) {
try {
ab = AssetBundle.LoadFromFile(path);
abUIMap.Add(path, ab);
T asset = (T)GameObject.Instantiate(ab.LoadAsset(assetName));
callBack?.Invoke(asset);
}
catch (Exception e) {
McLogger.Error("UI", nameof(UISetting), $"加载UIab包报错{e.Message}---->{e.StackTrace}");
callBack?.Invoke(null);
}
}
else {
callBack?.Invoke(null);
}
}
}
private string path = Application.streamingAssetsPath + $"/assetbundle/sequenceframe";//ab包路径
private void LoadAssetBundleFile(){
SimApp.UIRuntime.LoadUIformAB<GameObject>(path, "sequenceframe", (data) =>
{
if (data != null)
{
data.transform.SetParent(transform);
data.GetComponent<RectTransform>().localPosition = Vector3.zero;
data.GetComponent<RectTransform>().sizeDelta = Vector2.zero;
data.transform.localScale = Vector3.one;
}
});
}