TexturePacker自动生成UGUI纹理贴图+生成atlas工具

准备工作,首先需要安装TexturePacker-5.1.0-x64.msi,我使用的版本,因为软件付费,不需要担心水印问题.

其次,在unity中安装插件TexturePackerImporter.

需求方案是针对美术某目录下面所有子文件夹,对每一个文件夹里面所有素材做一个图集,生成spritesheet的metaData,方便程序用代码去控制调用,习惯NGUI的程序可以理解为atlas.


如果不想使用付费软件可以看下面这个网址:

https://blog.csdn.net/akak2010110/article/details/50777846

用这个办法也可以实现下面的需求

代码类加一个bat处理文件



[MenuItem("Tools/CMD/自动打包剧情Plot图集")]

    public static void ExecutePackage()

    {

        if (!(Directory.Exists("C:\\Program Files\\CodeAndWeb")

            || Directory.Exists("D:\\Program Files\\CodeAndWeb")

            || Directory.Exists("E:\\Program Files\\CodeAndWeb")

            || Directory.Exists("F:\\Program Files\\CodeAndWeb")

            || Directory.Exists("D:\\Program Files (x86)\\CodeAndWeb")

            || Directory.Exists("F:\\Program Files (x86)\\CodeAndWeb")))

        {

            EditorUtility.DisplayDialog("图集打包",

                    "生成失败" + "\n\n未安装图集打包软件TexturePacker", "确定");

            return;

        }

        string inputPath = PathManager.FileBasePath() + "/../../../art/人物立绘资源/";

        string outPath = PathManager.FileBasePath() + "/_Project/Modules/_Common/GUI/_OutTexture/Plot/";

        string[] files = Directory.GetDirectories(inputPath, "*", SearchOption.TopDirectoryOnly);

        for(int i =0;i< files.Length;i++)

        {

            //UnityEngine.Debug.Log(files[i]);

            string[] splits = files[i].Split('/');

            string folder_name = splits[splits.Length-1];

            ExecuteOnePackage(inputPath, folder_name, outPath);

        }

    }

    ///

    /// 调用bat命令打包

    ///

    /// 图集文件夹路径(打包时需要先cd到该路径), 需要先转换成绝对路径

    /// 图集文件夹名字

    /// 打包后图集放到的目标文件夹路径

    ///

    public static void ExecuteOnePackage(string dir, string folder_name, string atlasPath)

    {

        //参数解析

        //1=>bat命令路径

        //2=>是否弹出cmd窗口

        //3=>bat执行结束回调

        //4.1=>图集文件夹路径(打包时需要先cd到该路径)

        //4.2=>图集文件夹名字

        //4.3=>打包后图集放到的目标文件夹路径

        //4.4=>图集大小限制

        //4.5=>剔除透明方式

        try

        {

            string param1 = dir;

            string param2 = folder_name;

            string param3 = atlasPath;

            string param4 = "1024";

            string param5 = "None";

            string args = param1 + " " + param2 + " " + param3 + " " + param4 + " " + param5;

            //例子

            //string param = "D:/_MySpace/art/人物立绘资源/" + " "

            //                + "banban" + " "

            //                + "D:/_MySpace/client/StardomProject/Assets/_Project/Modules/_Common/GUI/_OutTexture/Plot/" + " "

            //                + "1024" + " "

            //                + "Trim";

            ProcessStartInfo startInfo = new ProcessStartInfo("D:/_MySpace/client/StardomProject/Assets/Editor/CMD/TPackageTool.bat", args);

            Process.Start(startInfo);

        }

        catch (Exception ex)

        {

            Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());

        }

    }



BAT文件内容:

::开始

@echo off

@echo ##TPBegin##

::更改当前目录为批处理本身的目录

cd /d %1

::pause

::设置路径

set cmd="C:/Program Files/CodeAndWeb/TexturePacker/bin/TexturePacker.exe"

::@echo %cmd%

if not exist %cmd%  (set cmd="D:/Program Files/CodeAndWeb/TexturePacker/bin/TexturePacker.exe")

if not exist %cmd%  (set cmd="E:/Program Files/CodeAndWeb/TexturePacker/bin/TexturePacker.exe")

if not exist %cmd%  (set cmd="F:/Program Files/CodeAndWeb/TexturePacker/bin/TexturePacker.exe")

if not exist %cmd%  (set cmd="I:/Program Files/CodeAndWeb/TexturePacker/bin/TexturePacker.exe")

if not exist %cmd%  (set cmd="C:/Program Files (x86)/CodeAndWeb/TexturePacker/bin/TexturePacker.exe")

::@echo %cmd%

::pause


::############TexturePacker参数###############

::--sheet

::生成的图片名

::--data

::生成的plist文件名

::--format ()

::生成的plist格式

::--enable-rotation/disable-rotation

::开启/关闭旋转,默认值和输出的格式有关系

::--opt

::设置输出图片的像素格式 一般默认RGBA8888

::--texturepath

::在生成的sheet文件的路径前加path

::--trim-sprite-names

::剪裁掉拼接图片的后缀名

::--trim-mode

::剪裁图片,即移除图片周围的透明像素

::None=不裁剪

::Trim=裁剪透明区域,但使用原始贴图大小

::Crop=裁剪透明区域,使用剪裁后的贴图大小(刷新位置)

::CropKeepPos=裁剪透明区域,使用裁剪后的贴图大小(位置不变)

::--size-constraints

::大小限制POT

::--force-squared

::长宽比一致

::--premultiply-alpha

::(unity不用这个指令)

::--shape-padding[精灵与精灵]

::即在spritesheet里面,设置精灵与精灵之间的间隔。如果你在你的游戏当中看到精灵的旁边有一些“杂图”的时候,你就可以增加这个精灵之间的间隔

::--border-padding[精灵与边界]

::即在spritesheet里面,设置精灵与精灵之间的间隔。如果你在你的游戏当中看到精灵的旁边有一些“杂图”的时候,你就可以增加这个精灵之间的间隔

::#############################################

::打包图集

for %%i in (%2) do ( 

    echo #package %%i

    %cmd% --format unity-texture2d ^

    --sheet %3%%i".png" ^

    --data %3%%i".tpsheet" ^

    --disable-rotation ^

    --opt RGBA8888 ^

    --smart-update ^

    --dither-fs-alpha %%i ^

    --force-publish ^

    --trim-sprite-names ^

    --trim-mode %5 ^

    --size-constraints POT ^

    --force-squared ^

    --max-size %4 ^

    --shape-padding 1 ^

--border-padding 0


::结束

@echo ##TPEnd##

::pause



自动成生atlas文件类

using UnityEngine;

using System.Collections;

using UnityEditor;

using System.IO;

public class UIAtalsEditor : Editor

{

    [MenuItem("Tools/CMD/自动创建Plot图集的Atlas")]

    public static void AutoCreateAtlasPrefab()

    {

        string inputPath = PathManager.FileBasePath() + "/_Project/Modules/_Common/GUI/_OutTexture/Plot/";

        string[] files = Directory.GetFiles(inputPath, "*.png", SearchOption.TopDirectoryOnly);

        for (int i = 0; i < files.Length; i++)

        {

            //Debug.Log(files[i]);

            string assetPath = "Assets" + files[i].Substring(Application.dataPath.Length);

            //Debug.Log(assetPath);

            Object assetObj = AssetDatabase.LoadAssetAtPath(assetPath);

            //Debug.Log(assetObj);

            Selection.activeObject = assetObj;

            CreateAtlasPrefab();

        }

        EditorUtility.DisplayDialog("", "全部生成图片的Atlas结束", "确定");

    }

    [MenuItem("Tools/UGUI/创建当前选中图集的Atlas")]

    public static void CreateAtlasPrefab()

    {

        if (Selection.activeObject != null)

        {

            string path = AssetDatabase.GetAssetPath(Selection.activeObject);

            TextureImporter importer = AssetImporter.GetAtPath(path) as TextureImporter;

            if (importer != null && importer.textureType == TextureImporterType.Sprite && importer.spriteImportMode == SpriteImportMode.Multiple)

            {

                UIAtals atlas = CreateInstance();

                object[] objs = AssetDatabase.LoadAllAssetsAtPath(path);

                atlas.spriteLists.Clear();

                foreach (object o in objs)

                {

                    if (o.GetType() == typeof(Texture2D))

                    {

                        atlas.mainText = o as Texture2D;

                    }

                    else if (o.GetType() == typeof(Sprite))

                    {

                        atlas.spriteLists.Add(o as Sprite);

                    }

                }

                string[] pathSplit = path.Split('G'); // Modules

                path = pathSplit[0] + "Resources/Atlas/" + Selection.activeObject.name.ToLower() + "_Atlas.prefab";

                Debug.Log(path);

                AssetDatabase.DeleteAsset(path);

                AssetDatabase.Refresh();

                GameObject go = new GameObject("prefab");

                PrefabUtility.SaveAsPrefabAsset(go,path);

                AssetDatabase.Refresh();

                AssetDatabase.AddObjectToAsset(atlas, path);

                AssetDatabase.SaveAssets();

                AssetDatabase.Refresh();

                DestroyImmediate(go);

            }

            else

            {

                EditorUtility.DisplayDialog("", "当前选中的不是图集图片", "确定");

            }

        }

    }

}


这个类内容可批量生成,也可单独生成某一个.生成的atlas放在Resources下.


生成的png


生成的atlas

再给一个读取的方法:

public Dictionary atlasmanage = new Dictionary();

    ///

    /// 加载图集

    ///

    /// 图集名称

    public UIAtals LoadAtals(string atlasName)

    {

        UIAtals atlas = Resources.Load("Atlas/" + atlasName);

        atlasmanage.Add(atlasName, atlas);

        return atlas;

    }

    //加载图集上的一个精灵  

    public Sprite LoadAtlasSprite(string atlasName, string spriteName)

    {

        UIAtals atlas;

        if (!atlasmanage.ContainsKey(atlasName))

        {

            atlas = LoadAtals(atlasName);

        }

        else

        {

            atlas = atlasmanage[atlasName];

        }

        if(atlas == null)

        {

            Log.Error("atlas 不存在,name = " + atlasName);

            return null;

        }

        Sprite sprite = atlas.GetSprite(spriteName);

        atlas = null;

        return sprite;

    }


一套流程如上 运行完全ok

全套代码GitHub上

https://github.com/linkongchen/TexturePacker-UGUI-Atlas


另做了一个工具,方便程序直接导出美术修改的图片....



需要和美术商量好路径文件夹名等

你可能感兴趣的:(TexturePacker自动生成UGUI纹理贴图+生成atlas工具)