UGUI(打包/加載)圖集、預制

接上篇:http://www.itdecent.cn/p/ec288fe5d58b

在測試過程中,發(fā)現(xiàn):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,不打進去不起沒發(fā)現(xiàn)啥問題
        //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 方便獲取依賴關(guān)系,一般正式項目會自己保存ab包的依賴關(guān)系
        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;

    }

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容