当前位置:首页 > 编程笔记 > 正文
已解决

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

来自网友在路上 174874提问 提问时间:2023-10-23 23:55:29阅读次数: 74

最佳答案 问答题库748位专家为你答疑解惑

前言:

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

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"Unity Editor 打包指定资源(AssetBundle)和加载指定资源":http://eshow365.cn/6-22826-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!