[置顶] unity利用Texture Packer一键打包图集(五)
2018-01-23 11:02
405 查看
打包图集可以有效的降低DrawCall,减轻渲染压力。unity对于打包图集的过程还是比较繁复的,作者推荐一下自己常用的方法,通过TexturePacker,打包图集到unity目录里,做到一键打包图集。
可以在下面的链接里,下载TexturePacker的安装包,并破解,查看实例demo,一键打包,并使用具体的小图图集。
将这个类放在Assets/Editor下
![](https://img-blog.csdn.net/20180123110037512?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMjI5MTExNjM=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
怎样使用打出来的图集呢?
![](https://img-blog.csdn.net/20180123110147963?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMjI5MTExNjM=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
点击下载资源点击打开链接
可以在下面的链接里,下载TexturePacker的安装包,并破解,查看实例demo,一键打包,并使用具体的小图图集。
将这个类放在Assets/Editor下
using System; using System.Collections.Generic; using UnityEngine; using System.IO; using UnityEditor; using System.Text; using System.Diagnostics; using System.Linq; using System.Xml; public class TexturePackerBuild : Editor { private const string BuildAll = "Tools/打包图集"; private const string BuildOne = "Assets/打包该图集"; /// <summary> /// 输出目录 /// </summary> private const string OutPutDirRoot = "Assets/Resources/Sprites/"; /// <summary> /// 小图目录 /// </summary> private const string OriginalDir = "Assets/Image"; /// <summary> /// TexturePacker的安装目录 /// </summary> private const string TPInstallDir = "E:\\TexturePacker\\bin\\TexturePacker.exe"; [MenuItem(BuildAll)] public static void BuildAllTP() { string inputPath = OriginalDir; string commandText = " --sheet {0}.png --data {1}.xml --format sparrow --trim-mode None --pack-mode Best --algorithm MaxRects --max-size 2048 --size-constraints POT --disable-rotation --scale 1 {2}"; 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]); GetImageName(fileName, ref sb); string name = Path.GetFileName(imagePath[i]); string sheetName = OutPutDirRoot + name; processCommand(TPInstallDir, string.Format(commandText, sheetName, sheetName, sb.ToString())); } } [MenuItem(BuildOne, false, 2)] public static void BuildOneTP() { var paths = Selection.assetGUIDs.Select(AssetDatabase.GUIDToAssetPath).Where(AssetDatabase.IsValidFolder).ToList(); if (paths.Count > 1) { EditorUtility.DisplayDialog("", "不能同时选择多个目录进行该操作!", "确定"); return; } string commandText = " --sheet {0}.png --data {1}.xml --format sparrow --trim-mode None --pack-mode Best --algorithm MaxRects --max-size 2048 --size-constraints POT --disable-rotation --scale 1 {2}"; UnityEngine.Debug.Log(paths[0]); StringBuilder sb = new StringBuilder(""); string[] fileName = Directory.GetFiles(paths[0]); GetImageName(fileName, ref sb); string name = Path.GetFileName(paths[0]); string sheetName = OutPutDirRoot + name; processCommand(TPInstallDir, string.Format(commandText, sheetName, sheetName, sb.ToString())); } private static StringBuilder GetImageName(string[] fileName, ref StringBuilder sb) { for (int j = 0; j < fileName.Length; j++) { string extenstion = Path.GetExtension(fileName[j]); if (extenstion == ".png") { sb.Append(fileName[j]); sb.Append(" "); } } return sb; } 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; 4000 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(); AssetDatabase.Refresh(); BuildTexturePacker(); ClearOtherFiles(); AssetDatabase.Refresh(); } /// <summary> /// 清理原始图 /// </summary> private static void ClearOtherFiles() { string[] fileName = Directory.GetFiles(OutPutDirRoot); if (fileName != null && fileName.Length > 0) { for (int i = 0; i < fileName.Length; i++) { string extenstion = Path.GetExtension(fileName[i]); if (extenstion == ".png" || extenstion == ".xml") { File.Delete(fileName[i]); } } } } public static void BuildTexturePacker() { string[] imagePath = Directory.GetFiles(OutPutDirRoot); foreach (string path in imagePath) { if (Path.GetExtension(path) == ".png" || Path.GetExtension(path) == ".PNG") { Texture2D texture = AssetDatabase.LoadAssetAtPath<Texture2D>(path); UnityEngine.Debug.Log(texture.name); string rootPath = OutPutDirRoot + 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)) { UnityEngine.Debug.Log("exite: " + pngPath); asetImp = GetTextureIpter(pngPath); SaveBoreder(tIpterMap, asetImp); File.Delete(pngPath); } File.Copy(OutPutDirRoot + texture.name + ".png", pngPath); } else { Directory.CreateDirectory(rootPath); File.Copy(OutPutDirRoot + texture.name + ".png", pngPath); } AssetDatabase.Refresh(); FileStream fs = new FileStream(OutPutDirRoot + 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>(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("{0}{1}/{2}.png",OutPutDirRoot, 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"); 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(); } } 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; } }修改这个类里的常量,可以修改小图目录,输出目录和TexturePacker的安装目录。
怎样使用打出来的图集呢?
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Test4 : MonoBehaviour { // Use this for initialization void Start () { //resources加载 var sprites = Resources.LoadAll<Sprite>("Sprites/main/main"); Debug.LogError(sprites[0]); //将图集打包成assetsbundle加载 //加载assetsbundle里的图片,先取得assetbundle再loadall //var asset = www.assetBundle; //var sprites = asset.LoadAllAssets(typeof(Sprite)); } }如果你觉得有用,想请我喝杯咖啡的话,扫下面的赞赏码吧0.0
点击下载资源点击打开链接
相关文章推荐
- Unity 利用UGUI打包图集,动态加载sprite资源
- Unity下Android利用Ant构建打包
- Unity一键图集生成工具,附源码 (基于NGUI和TexturePacker)
- Unity游戏开发——UnityUGUI打包图集
- Unity5 Sprite 图集打包 AssetBundle 更新探索
- Unity ios、android、pc一键打包(一)
- [置顶] 利用OLAMI在unity游戏中加入中文语音控制(一)
- Unity5 Sprite 图集打包 AssetBundle 更新探索
- unity2d游戏开发大坑之图集打包
- 【unity】unity自动化打包——利用XUPorter解决xcode8问题
- 【Unity】像素图片用NGUI编辑打包成图集
- Unity4.6 UGUI 图片打包设置(小图打包成图集 SpritePacker)
- Unity打包exe去边框,置顶,透明,透明穿透解决方案
- [置顶] Unity打包exe后去除原生窗口,使用自己的窗口控制UI,修改了网上的很多bug
- Unity一键打包为APK文件(windows平台)
- Win7使用jenkins一键打包unity工程的apk包
- [置顶] AndroidStudio 利用Gradle打包添加上版本名和版本号
- Unity4.6 UGUI 图片打包设置(小图打包成图集 SpritePacker)
- ios 新的一键打包方式(基于Unity5.x)
- [置顶] UGUI之打包图集与使用