UGUI(打包/加载)图集、预制

接上篇:https://www.jianshu.com/p/ec288fe5d58b

在测试过程中,发现:ProjectSettings > Editor > Mode 不等于 AlwaysEnabled 时,从AB中加载的预制的UI显示不出来,不知道原因
打包预制、图集
using System.Collections.Generic;
using UnityEditor;

/// <summary>
/// 用来打包的工具脚本
/// </summary>
public class BuildToolsEditor : Editor
{
    /*
        打包图集之前,应确保ProjectSettings > Editor > Mode == AlwaysEnabled
        AssetBundleBuild.assetNames             //这个文件在项目中的路径,加上后缀名
        AssetBundleBuild.addressableNames       //从这个AB包中LoadAsset时,要用这个名字
        AssetBundleBuild.assetBundleName        //这个AB包叫啥名字,可以在前边加上路径路径
        AssetBundleBuild.assetBundleVariant     //扩展名
    */
    
    [MenuItem("Tools/打包UI(图集和预制)")]
    static void onBuildAtlas()
    {
        List<AssetBundleBuild> AssetBundleLists = AssetBundleCollectEditor.GetAssetBundleBuilds_UI();
        BuildPipeline.BuildAssetBundles(@"E:\UnityProject\AssetBundles", AssetBundleLists.ToArray(), BuildAssetBundleOptions.ChunkBasedCompression, BuildTarget.StandaloneWindows64);
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }
}
收集AssetBundleBuild
#if UNITY_EDITOR

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

/// <summary>
/// 专用于收集AssetBundleBuild的脚本
/// </summary>
public static class AssetBundleCollectEditor
{

    /// <summary>
    /// 收集UI类型的AssetBundleBuild
    /// </summary>
    /// <returns>AssetBundleBuild列表</returns>
    public static List<AssetBundleBuild> GetAssetBundleBuilds_UI()
    {
        List<AssetBundleBuild> AssetBundleLists = new List<AssetBundleBuild>();

        string rootPath = Path.Combine(Application.dataPath, "UI/Modules");
        //获取文件夹下的一级子文件夹
        string[] allModule = Directory.GetDirectories(rootPath);
        foreach (string modulePath in allModule)
        {
            //获取模块名
            string moduleName = Path.GetFileName(modulePath);
            //模块下是否存在方图片的文件夹
            //Images下不允许直接方图片,需要放在Images的子文件夹中,如:Images/Common,Images/bg 等
            string imagesDire = Path.Combine(modulePath, "Images");
            bool isExists_imagesDire = Directory.Exists(imagesDire);
            if (isExists_imagesDire)
            {
                string[] allImagesDire = Directory.GetDirectories(imagesDire);
                foreach (string imageDire in allImagesDire)
                {
                    string direPath = "Assets" + imageDire.Substring(Application.dataPath.Length);
                    direPath = direPath.Replace("\\", "/");
                    AddBuildAtlas(moduleName, direPath, AssetBundleLists);
                }
            }

            string prefabsDire = Path.Combine(modulePath, "Prefabs");
            bool isExists_prefabsDire = Directory.Exists(prefabsDire);
            if (isExists_prefabsDire)
            {
                string direPath = "Assets" + prefabsDire.Substring(Application.dataPath.Length);
                direPath = direPath.Replace("\\", "/");
                AddBuildPrefab(moduleName, direPath, AssetBundleLists);
            }
        }

        return AssetBundleLists;
    }
    /// <summary>
    /// 添加图集
    /// </summary>
    /// <param name="moduleName">模块名</param>
    /// <param name="imageDire">文件夹路径</param>
    static void AddBuildAtlas(string moduleName, string imageDire, List<AssetBundleBuild> AssetBundleLists)
    {
        string[] allImagePath = Directory.GetFiles(imageDire, "*.png");
        if (allImagePath.Length <= 0)
            return;
        string direName = Path.GetFileNameWithoutExtension(imageDire);
        string currentAtlasName = $"Atlas_{moduleName}_{direName}";

        AssetBundleBuild abBuild = new AssetBundleBuild();
        List<string> assetNamesArray = new List<string>();
        List<string> addressableNamesArray = new List<string>();

        foreach (var image in allImagePath)
        {
            string imageName = Path.GetFileNameWithoutExtension(image);
            string imagePath = image.Replace("\\", "/");
            assetNamesArray.Add(imagePath);
            addressableNamesArray.Add(imageName);
        }

        ////把图集打进AB后,可以在AB中通过图集加载Sprite,不打进去不起没发现啥问题
        //assetNamesArray.Add($"{imageDire}/{currentAtlasName}.spriteatlas");
        //addressableNamesArray.Add(currentAtlasName);

        abBuild.assetNames = assetNamesArray.ToArray();
        abBuild.addressableNames = addressableNamesArray.ToArray();
        abBuild.assetBundleName = $"Assets/UI/Modules/{moduleName}/{currentAtlasName}";
        abBuild.assetBundleVariant = "unity3d";
        AssetBundleLists.Add(abBuild);
    }
    /// <summary>
    /// 添加UI预制体
    /// </summary>
    /// <param name="moduleName">模块名</param>
    /// <param name="prefabDire">文件夹路径</param>
    static void AddBuildPrefab(string moduleName, string prefabDire, List<AssetBundleBuild> AssetBundleLists)
    {
        string[] allPrefabPath = Directory.GetFiles(prefabDire, "*.prefab");
        if (allPrefabPath.Length <= 0)
            return;

        foreach (var prefab in allPrefabPath)
        {
            AssetBundleBuild abBuild = new AssetBundleBuild();
            List<string> assetNamesArray = new List<string>();
            List<string> addressableNamesArray = new List<string>();

            string prefabName = Path.GetFileNameWithoutExtension(prefab);
            string prefabPath = prefab.Replace("\\", "/");
            assetNamesArray.Add(prefabPath);

            addressableNamesArray.Add(prefabName);
            string assetBundleName = $"Assets/UI/Modules/{moduleName}/{prefabName}";

            abBuild.assetNames = assetNamesArray.ToArray();
            abBuild.addressableNames = addressableNamesArray.ToArray();
            abBuild.assetBundleName = assetBundleName;
            abBuild.assetBundleVariant = "unity3d";
            AssetBundleLists.Add(abBuild);
        }
    }



}

#endif
加载AB中的预制、图集、Sprite
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.U2D;
using UnityEngine.UI;

public class LoadUIScript : MonoBehaviour
{
    public Transform Parent;

    public Image showImage1;
    public Image showImage2;
    public Image showImage3;

    void Start()
    {

        string assetPath = @"E:\UnityProject\AssetBundles";

        ////先加载 Manifest 方便获取依赖关系,一般正式项目会自己保存ab包的依赖关系
        AssetBundle manifestAB = AssetBundle.LoadFromFile(Path.Combine(assetPath, "AssetBundles"));
        AssetBundleManifest assetBundleManifest = manifestAB.LoadAsset<AssetBundleManifest>("AssetBundleManifest");

        //通过打包时的assetBundleName来获取这个ab包的依赖
        string[] strs = assetBundleManifest.GetAllDependencies("assets/ui/modules/bag/ui_testpanel1.unity3d");
        foreach (string name in strs)
        {
            //加载依赖,实际需要把这些加载的依赖都保存起来
            AssetBundle dep = AssetBundle.LoadFromFile(Path.Combine(assetPath, name));
            Debug.Log("依赖加载:" + name);
        }
        //加载ab包
        AssetBundle panelAB = AssetBundle.LoadFromFile(assetPath + "/assets/ui/modules/bag/ui_testpanel1.unity3d");
        //加载ab包中的预制体
        GameObject wallPrefab = panelAB.LoadAsset<GameObject>("UI_testPanel1");
        var obj = Instantiate(wallPrefab);
        obj.transform.SetParent(Parent);
        obj.transform.localScale = Vector3.one;
        obj.transform.localPosition = Vector3.zero;



        //加载图集并获取图集中的图片
        //一下两种效果一样

        //AssetBundle atlas_ab = AssetBundle.LoadFromFile(Path.Combine(assetPath, "assets/ui/modules/bag/atlas_bag_bg.unity3d"));
        //Sprite sprite1 = atlas_ab.LoadAsset<Sprite>("bg_blue");
        //showImage1.sprite = sprite1;
        //Sprite sprite2 = atlas_ab.LoadAsset<Sprite>("bg_white");
        //showImage2.sprite = sprite2;
        //Sprite sprite3 = atlas_ab.LoadAsset<Sprite>("img_check");
        //showImage3.sprite = sprite3;


        //如果把图集也打进AB包中,可以这样加载
        //SpriteAtlas spriteAtlas = atlas_ab.LoadAsset<SpriteAtlas>("Atlas_Bag_bg");
        //Sprite sprite1 = spriteAtlas.GetSprite("bg_blue");
        //showImage1.sprite = sprite1;
        //Sprite sprite2 = spriteAtlas.GetSprite("bg_white");
        //showImage2.sprite = sprite2;
        //Sprite sprite3 = spriteAtlas.GetSprite("img_check");
        //showImage3.sprite = sprite3;

    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,820评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,648评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,324评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,714评论 1 297
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,724评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,328评论 1 310
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,897评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,804评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,345评论 1 318
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,431评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,561评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,238评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,928评论 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,417评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,528评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,983评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,573评论 2 359