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;

    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。