Unity Editor 打包指定资源(AssetBundle)和加载指定资源

编程入门 行业动态 更新时间:2024-10-23 09:30:28

Unity Editor 打包指定<a href=https://www.elefans.com/category/jswz/34/1770980.html style=资源(AssetBundle)和加载指定资源"/>

Unity Editor 打包指定资源(AssetBundle)和加载指定资源

前言:

        一般用于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;}});}

更多推荐

Unity Editor 打包指定资源(AssetBundle)和加载指定资源

本文发布于:2023-12-06 09:51:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1667208.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:资源   加载   Unity   Editor   AssetBundle

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!