首页 > 其他分享 >Unity的UGUI用TexturePacker全自动打图集,包括九宫格切图信息

Unity的UGUI用TexturePacker全自动打图集,包括九宫格切图信息

时间:2023-05-19 19:32:33浏览次数:51  
标签:string -- 切图 九宫格 texture start Unity TexturePacker name

@TOC

前言

最近在学习UGUI的打图集,之前一直在用SpritePacker和Sprite Atlas打图集,现在记录下另一种打图集方式:TexturePacker 主要是讲如何自动打图集到Unity,并且不丢掉九宫格信息,以及一些参数的设置

环境准备

1.unity版本2019.4.10f1

2.TexturePacker安装官网,支持正版,支持正版,支持正版https://www.codeandweb.com/texturepacker

3.TexturePacker安装Po Jie 版本点击这下载

4.unity中安装TexturePacker Importer点击这下载,也可以在unity商店搜索TexturePacker Importer安装

5.了解一下TexturePacker的命令行参数: 打开命令行工具并CD到TexturePacker的安装目录,输入 TexturePacker –help,会出现该版本的TP的一些命令行参数。

Unity的UGUI用TexturePacker全自动打图集,包括九宫格切图信息_Parse

实现过程

把要打图集的小图放到指定的文件夹,我是放在

Unity的UGUI用TexturePacker全自动打图集,包括九宫格切图信息_Parse_02

打出来的图放在Assets/SheetsByTP这个文件夹下,打好的图集会放在Assets/TexturePacker/icon文件夹下。 写两个编辑器脚本,放在Editor文件夹下,废话不多说上代码:

#if UNITY_EDITOR
using System;
using UnityEngine;
using System.IO;
using UnityEditor;
using System.Text;
using System.Diagnostics;
using Debug = UnityEngine.Debug;

public class CommandBuild : Editor
{

    [MenuItem("Tools/SpritesPacker/CommandBuild")]
    public static void BuildTexturePacker()
    {
        //选择并设置TP命令行的参数和参数值(包括强制生成2048*2048的图集 --width 2048 --height 2048)
        string commandText = " --sheet {0}.png --data {1}.xml --format sparrow --trim-mode None --pack-mode Best  --algorithm MaxRects --width 2048 --height 2048 --max-size 2048 --size-constraints POT  --disable-rotation --scale 1 {2}" ;
        string inputPath = string.Format ("{0}/Images", Application.dataPath);//小图目录
        string outputPath = string.Format ("{0}/TexturePacker", Application.dataPath);//用TP打包好的图集存放目录
        string[] imagePath = Directory.GetDirectories (inputPath); 
        
        for (int i = 0; i < imagePath.Length; i++) 
        {
            UnityEngine.Debug.Log (imagePath [i]);
            StringBuilder sb = new StringBuilder("");
            string[] fileName = Directory.GetFiles(imagePath[i]);
            for (int j = 0; j < fileName.Length; j++)
            {
                string extenstion = Path.GetExtension(fileName[j]);
                if (extenstion == ".png")
                {
                    sb.Append(fileName[j]);
                    sb.Append("  ");
                    
                    
                }
                UnityEngine.Debug.Log("fileName [j]:" + fileName[j]);
            }
            string name = Path.GetFileName(imagePath [i]);
            string outputName = string.Format ("{0}/TexturePacker/{1}/{2}", Application.dataPath,name,name);
            string sheetName = string.Format("{0}/SheetsByTP/{1}", Application.dataPath, name);
            //执行命令行
            processCommand("E:\\Program Files (x86)\\CodeAndWeb\\TexturePacker\\bin\\TexturePacker.exe", string.Format(commandText, sheetName, sheetName, sb.ToString()));
        }
        AssetDatabase.Refresh();
    }
    private static void processCommand(string command, string argument)
    {
        ProcessStartInfo start = new ProcessStartInfo(command);
        start.Arguments = argument;
        start.CreateNoWindow = false;
        start.ErrorDialog = true;
        start.UseShellExecute = false;

        if(start.UseShellExecute){
            start.RedirectStandardOutput = false;
            start.RedirectStandardError = false;
            start.RedirectStandardInput = false;
        } else{
            start.RedirectStandardOutput = true;
            start.RedirectStandardError = true;
            start.RedirectStandardInput = true;
            start.StandardOutputEncoding = System.Text.UTF8Encoding.UTF8;
            start.StandardErrorEncoding = System.Text.UTF8Encoding.UTF8;
        }

        Process p = Process.Start(start);
        if(!start.UseShellExecute)
        {
            UnityEngine.Debug.Log(p.StandardOutput.ReadToEnd());
            UnityEngine.Debug.Log(p.StandardError.ReadToEnd());
        }

        p.WaitForExit();
        p.Close();
    }
}
#endif

添加第二个脚本在Editor下

#if UNITY_EDITOR
using UnityEngine;
using System;
using System.IO;
using UnityEditor;
using System.Collections.Generic;
using System.Xml;
public class MySpritesPacker : Editor
{
    [MenuItem("Tools/SpritesPacker/TexturePacker")]
    public static void BuildTexturePacker()
    {
        string inputPath = string.Format("{0}/SheetsByTP/", Application.dataPath);
        string[] imagePath = Directory.GetFiles(inputPath);
        foreach (string path in imagePath)
        {
            if (Path.GetExtension(path) == ".png" || Path.GetExtension(path) == ".PNG")
            {
                string sheetPath = GetAssetPath(path);
                Texture2D texture = AssetDatabase.LoadAssetAtPath<Texture2D>(sheetPath);
                Debug.Log(texture.name);
                string rootPath = string.Format("{0}/TexturePacker/{1}", Application.dataPath,texture.name);
                string pngPath = rootPath + "/" + texture.name + ".png";
                TextureImporter asetImp = null;
                Dictionary<string, Vector4> tIpterMap = new Dictionary<string,Vector4>();
                if (Directory.Exists(rootPath))
                {
                    if(File.Exists(pngPath))
                    {
                        Debug.Log("exite: " + pngPath);
                        //asetImp = GetTextureIpter(pngPath);
                        //SaveBoreder(tIpterMap, asetImp);
                        File.Delete(pngPath);
                    }
                    File.Copy(inputPath + texture.name + ".png", pngPath);
                }
                else
                {
                    Directory.CreateDirectory(rootPath);
                    File.Copy(inputPath + texture.name + ".png", pngPath);
                }
                AssetDatabase.Refresh();
                FileStream fs = new FileStream(inputPath + texture.name + ".xml", FileMode.Open);
                StreamReader sr = new StreamReader(fs);
                string jText = sr.ReadToEnd();
                fs.Close();
                sr.Close();
                XmlDocument xml = new XmlDocument();
                xml.LoadXml(jText);
                XmlNodeList elemList = xml.GetElementsByTagName("SubTexture");
                WriteMeta(elemList, texture.name, tIpterMap);
            }
        }
        AssetDatabase.Refresh();
    }
    //如果这张图集已经拉好了9宫格,需要先保存起来
    static void SaveBoreder(Dictionary<string,Vector4> tIpterMap,TextureImporter tIpter)
    {
        for(int i = 0,size = tIpter.spritesheet.Length; i < size; i++)
        {
            tIpterMap.Add(tIpter.spritesheet[i].name, tIpter.spritesheet[i].border);
        }
    }

    static TextureImporter GetTextureIpter(Texture2D texture)
    {
        TextureImporter textureIpter = null;
        string impPath = AssetDatabase.GetAssetPath(texture);
        textureIpter = TextureImporter.GetAtPath(impPath) as TextureImporter;
        return textureIpter;
    }

    static TextureImporter GetTextureIpter(string path)
    {
        TextureImporter textureIpter = null;
        Texture2D textureOrg = AssetDatabase.LoadAssetAtPath<Texture2D>(GetAssetPath(path));
        string impPath = AssetDatabase.GetAssetPath(textureOrg);
        textureIpter =  TextureImporter.GetAtPath(impPath) as TextureImporter;
        return textureIpter;
    }
    //写信息到SpritesSheet里
    static void WriteMeta(XmlNodeList elemList, string sheetName,Dictionary<string,Vector4> borders)
    {
        string path = string.Format("Assets/TexturePacker/{0}/{1}.png", sheetName, sheetName);
        Texture2D texture = AssetDatabase.LoadAssetAtPath <Texture2D>(path);
        string impPath = AssetDatabase.GetAssetPath(texture);
        TextureImporter asetImp = TextureImporter.GetAtPath(impPath) as TextureImporter;
        SpriteMetaData[] metaData = new SpriteMetaData[elemList.Count];
        for (int i = 0, size = elemList.Count; i < size; i++)
        {
            XmlElement node = (XmlElement)elemList.Item(i);
            Rect rect = new Rect();
            rect.x = int.Parse(node.GetAttribute("x"));
            rect.y = texture.height - int.Parse(node.GetAttribute("y")) - int.Parse(node.GetAttribute("height"));
            rect.width = int.Parse(node.GetAttribute("width"));
            rect.height = int.Parse(node.GetAttribute("height"));
            metaData[i].rect = rect;
            metaData[i].pivot = new Vector2(0.5f, 0.5f);
            metaData[i].name = node.GetAttribute("name");
            //读取源文件的meta文件,获取spriteBorder九宫格信息,写进图集中
            string sourcePath= string.Format("{0}/Images/{1}/{2}.png", Application.dataPath,sheetName, node.GetAttribute("name"));
            Vector4 sourceBorder= GetTextureIpter(sourcePath).spriteBorder;
            Debug.Log("图片的路径"+sourcePath+"图片的border"+sourceBorder.ToString());
            metaData[i].border = sourceBorder;
            // if (borders.ContainsKey(metaData[i].name))
            // {
            //     metaData[i].border = borders[metaData[i].name];
            // }
        }
        asetImp.spritesheet = metaData;
        asetImp.textureType = TextureImporterType.Sprite;
        asetImp.spriteImportMode = SpriteImportMode.Multiple;
        asetImp.mipmapEnabled = false;
        asetImp.SaveAndReimport();
    }

    static string GetAssetPath(string path)
    {
        string[] seperator = { "Assets" };
        string p = "Assets" + path.Split(seperator, StringSplitOptions.RemoveEmptyEntries)[1];
        return p;
    }

}

internal class TextureIpter
{
    public string spriteName = "";
    public Vector4 border = new Vector4();
    public TextureIpter() { }
    public TextureIpter(string spriteName, Vector4 border)
    {
        this.spriteName = spriteName;
        this.border = border;
    }
}
#endif

按下Tools/SpritesPacker/CommandBuild

按下Tools/SpritesPacker/TexturePacker 图集就打好了

Unity的UGUI用TexturePacker全自动打图集,包括九宫格切图信息_Parse_03

注意

1.如果有九宫格信息,注意名字要一致,可以查看图片的Border来查看九宫格信息

Unity的UGUI用TexturePacker全自动打图集,包括九宫格切图信息_Parse_04

2.各文件路径可以在脚本里自行修改,如果需要设置其他参数,可以在命令里面自行添

标签:string,--,切图,九宫格,texture,start,Unity,TexturePacker,name
From: https://blog.51cto.com/u_16023649/6314688

相关文章

  • Unity中级客户端开发工程师的进阶之路
    上期UWA技能成长系统之《Unity高级客户端开发工程师的进阶之路》得到了很多Unity开发者的肯定。通过系统的学习,可以掌握游戏性能瓶颈定位的方法和常见的CPU、GPU、内存相关的性能优化方法。UWA技能成长系统是UWA根据学员的职业发展目标,提供技能学习的推荐路径,再将所需学习内容按......
  • Unity 愤怒的小鸟
    1.springjoint2D组件    弹簧关节。就是弹弓上伸缩弹性的绳子,添加组件会自动加一个刚体组件,把这个组件加在小鸟身上2.弹弓添加刚体组件Rigibody2D,把BodyType改成static,意思是只让他挂组件,不让他受重力    --世界坐标是以屏幕中心为原点,左负右正,下负上正  ......
  • unity基础2
       向量夹角的余弦值V  然后弧度转角度,用关键字RadDeg 也可以直接求角度   ------------------------------------------------------------------------------------------------------------------------------------------------------------------------......
  • Unity 打包出来的apk安装到Oculus Quest2黑屏或闪退
    用Unity2022版本打包了一个空工程,安装到Oculus上,发现一直黑屏,然后又安装了一下Unity2019版本,再打包,直接闪退看了一下日志,有如下报错:WSystem.err:java.lang.RuntimeException:RequestedAPIversion(api=1.1.51.0,driver=0)isincompatiblewiththecurrentlyinstalled......
  • Unity 热更新学习笔记二:异步加载
    在学习异步加载前应该学习一下Untiy中如何进行性能分析为什么热更新要学习性能分析?在热更新的过程其实也就是一种资源加载的过程,而涉及到资源加载就不得不提性能分析。因为资源的加载通常是异步加载的,如果把资源都统合在一起加载游戏界面就会卡住,这是我们不希望发生的事情。Unt......
  • Burp Suite Professional / Community 2023.5 (macOS, Linux, Windows) - Web 应用安
    BurpSuiteProfessional/Community2023.5(macOS,Linux,Windows)-Web应用安全、测试和扫描BurpSuiteProfessional,Test,find,andexploitvulnerabilities.请访问原文链接:https://sysin.org/blog/burp-suite-pro-2023/,查看最新版。原创作品,转载请保留出处。作者......
  • Unity 角色移动2D动画模块
    usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;[RequireComponent(typeof(SpriteRenderer))]publicclassSpriteAnimator:MonoBehaviour{privateSpriteRendererspriteRenderer;[SerializeField]privateSpriteid......
  • 视频直播网站源码,uni-app左右平分九宫格样式
    视频直播网站源码,uni-app左右平分九宫格样式1.template:布局 <template>  <viewclass="content">    <viewclass="cp-xiangmu"v-for="iteminimgs">      <image:src="item.imgurl"class='cp_tupian�......
  • Unity3D高级编程主程手记 学习笔记一:软件架构
    架构的重要性不言而喻,对于一个项目来说如果在开发初期就能确定好所使用的引擎,API以及各种系统之间的层次关系,那对于后续的开发一定会是事半功倍的,我想作者将软件架构放在第一章一定是想让Untiy程序员尤其是主程,一定要认真的对待架构这件事。优秀的架构师不仅需要对每个子系统的决......
  • Unity 2021.3.6f1 UnityHub 3.0.1 Win 安装图解 Unity 2021.3
     Unity2021.3.6f1UnityHub3.0.1Win安装图解Unity3D是一款跨平台的游戏引擎软件,它可用于开发2D、3D游戏以及虚拟现实、增强现实等应用程序。Unity3D提供了丰富的功能和工具,让开发者可以快速地创建高质量、交互性强的游戏和应用程序。Unity3D支持多种编程语......