TexturePacker Tools

打包图集可以有效的降低DrawCall,减轻渲染压力。unity对于打包图集的过程还是比较繁复的,作者推荐一下自己常用的方法,通过TexturePacker,打包图集到unity目录里,做到一键打包图集。

可以在下面的链接里,下载TexturePacker的安装包,并破解,查看实例demo,一键打包,并使用具体的小图图集。

将这个类放在Assets/Editor下


 
 
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System.IO;
  5. using UnityEditor;
  6. using System.Text;
  7. using System.Diagnostics;
  8. using System.Linq;
  9. using System.Xml;
  10. public class TexturePackerBuild : Editor
  11. {
  12. private const string BuildAll = "Tools/打包图集";
  13. private const string BuildOne = "Assets/打包该图集";
  14. /// <summary>
  15. /// 输出目录
  16. /// </summary>
  17. private const string OutPutDirRoot = "Assets/Resources/Sprites/";
  18. /// <summary>
  19. /// 小图目录
  20. /// </summary>
  21. private const string OriginalDir = "Assets/Image";
  22. /// <summary>
  23. /// TexturePacker的安装目录
  24. /// </summary>
  25. private const string TPInstallDir = "E:\\TexturePacker\\bin\\TexturePacker.exe";
  26. [ MenuItem(BuildAll)]
  27. public static void BuildAllTP()
  28. {
  29. string inputPath = OriginalDir;
  30. 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}";
  31. string[] imagePath = Directory.GetDirectories(inputPath);
  32. for ( int i = 0; i < imagePath.Length; i++)
  33. {
  34. UnityEngine.Debug.Log(imagePath[i]);
  35. StringBuilder sb = new StringBuilder( "");
  36. string[] fileName = Directory.GetFiles(imagePath[i]);
  37. GetImageName(fileName, ref sb);
  38. string name = Path.GetFileName(imagePath[i]);
  39. string sheetName = OutPutDirRoot + name;
  40. processCommand(TPInstallDir, string.Format(commandText, sheetName, sheetName, sb.ToString()));
  41. }
  42. }
  43. [ MenuItem(BuildOne, false, 2)]
  44. public static void BuildOneTP()
  45. {
  46. var paths = Selection.assetGUIDs.Select(AssetDatabase.GUIDToAssetPath).Where(AssetDatabase.IsValidFolder).ToList();
  47. if (paths.Count > 1)
  48. {
  49. EditorUtility.DisplayDialog( "", "不能同时选择多个目录进行该操作!", "确定");
  50. return;
  51. }
  52. 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}";
  53. UnityEngine.Debug.Log(paths[ 0]);
  54. StringBuilder sb = new StringBuilder( "");
  55. string[] fileName = Directory.GetFiles(paths[ 0]);
  56. GetImageName(fileName, ref sb);
  57. string name = Path.GetFileName(paths[ 0]);
  58. string sheetName = OutPutDirRoot + name;
  59. processCommand(TPInstallDir, string.Format(commandText, sheetName, sheetName, sb.ToString()));
  60. }
  61. private static StringBuilder GetImageName(string[] fileName, ref StringBuilder sb)
  62. {
  63. for ( int j = 0; j < fileName.Length; j++)
  64. {
  65. string extenstion = Path.GetExtension(fileName[j]);
  66. if (extenstion == ".png")
  67. {
  68. sb.Append(fileName[j]);
  69. sb.Append( " ");
  70. }
  71. }
  72. return sb;
  73. }
  74. private static void processCommand(string command, string argument)
  75. {
  76. ProcessStartInfo start = new ProcessStartInfo(command);
  77. start.Arguments = argument;
  78. start.CreateNoWindow = false;
  79. start.ErrorDialog = true;
  80. start.UseShellExecute = false;
  81. if (start.UseShellExecute)
  82. {
  83. start.RedirectStandardOutput = false;
  84. start.RedirectStandardError = false;
  85. start.RedirectStandardInput = false;
  86. }
  87. else
  88. {
  89. start.RedirectStandardOutput = true;
  90. start.RedirectStandardError = true;
  91. start.RedirectStandardInput = true;
  92. start.StandardOutputEncoding = System.Text.UTF8Encoding.UTF8;
  93. start.StandardErrorEncoding = System.Text.UTF8Encoding.UTF8;
  94. }
  95. Process p = Process.Start(start);
  96. if (!start.UseShellExecute)
  97. {
  98. UnityEngine.Debug.Log(p.StandardOutput.ReadToEnd());
  99. UnityEngine.Debug.Log(p.StandardError.ReadToEnd());
  100. }
  101. p.WaitForExit();
  102. p.Close();
  103. AssetDatabase.Refresh();
  104. BuildTexturePacker();
  105. ClearOtherFiles();
  106. AssetDatabase.Refresh();
  107. }
  108. /// <summary>
  109. /// 清理原始图
  110. /// </summary>
  111. private static void ClearOtherFiles()
  112. {
  113. string[] fileName = Directory.GetFiles(OutPutDirRoot);
  114. if (fileName != null && fileName.Length > 0)
  115. {
  116. for ( int i = 0; i < fileName.Length; i++)
  117. {
  118. string extenstion = Path.GetExtension(fileName[i]);
  119. if (extenstion == ".png" || extenstion == ".xml")
  120. {
  121. File.Delete(fileName[i]);
  122. }
  123. }
  124. }
  125. }
  126. public static void BuildTexturePacker()
  127. {
  128. string[] imagePath = Directory.GetFiles(OutPutDirRoot);
  129. foreach ( string path in imagePath)
  130. {
  131. if (Path.GetExtension(path) == ".png" || Path.GetExtension(path) == ".PNG")
  132. {
  133. Texture2D texture = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
  134. UnityEngine.Debug.Log(texture.name);
  135. string rootPath = OutPutDirRoot + texture.name;
  136. string pngPath = rootPath + "/" + texture.name + ".png";
  137. TextureImporter asetImp = null;
  138. Dictionary< string, Vector4> tIpterMap = new Dictionary< string, Vector4>();
  139. if (Directory.Exists(rootPath))
  140. {
  141. if (File.Exists(pngPath))
  142. {
  143. UnityEngine.Debug.Log( "exite: " + pngPath);
  144. asetImp = GetTextureIpter(pngPath);
  145. SaveBoreder(tIpterMap, asetImp);
  146. File.Delete(pngPath);
  147. }
  148. File.Copy(OutPutDirRoot + texture.name + ".png", pngPath);
  149. }
  150. else
  151. {
  152. Directory.CreateDirectory(rootPath);
  153. File.Copy(OutPutDirRoot + texture.name + ".png", pngPath);
  154. }
  155. AssetDatabase.Refresh();
  156. FileStream fs = new FileStream(OutPutDirRoot + texture.name + ".xml", FileMode.Open);
  157. StreamReader sr = new StreamReader(fs);
  158. string jText = sr.ReadToEnd();
  159. fs.Close();
  160. sr.Close();
  161. XmlDocument xml = new XmlDocument();
  162. xml.LoadXml(jText);
  163. XmlNodeList elemList = xml.GetElementsByTagName( "SubTexture");
  164. WriteMeta(elemList, texture.name, tIpterMap);
  165. }
  166. }
  167. AssetDatabase.Refresh();
  168. }
  169. //如果这张图集已经拉好了9宫格,需要先保存起来
  170. static void SaveBoreder(Dictionary<string, Vector4> tIpterMap, TextureImporter tIpter)
  171. {
  172. for ( int i = 0, size = tIpter.spritesheet.Length; i < size; i++)
  173. {
  174. tIpterMap.Add(tIpter.spritesheet[i].name, tIpter.spritesheet[i].border);
  175. }
  176. }
  177. static TextureImporter GetTextureIpter(Texture2D texture)
  178. {
  179. TextureImporter textureIpter = null;
  180. string impPath = AssetDatabase.GetAssetPath(texture);
  181. textureIpter = TextureImporter.GetAtPath(impPath) as TextureImporter;
  182. return textureIpter;
  183. }
  184. static TextureImporter GetTextureIpter(string path)
  185. {
  186. TextureImporter textureIpter = null;
  187. Texture2D textureOrg = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
  188. string impPath = AssetDatabase.GetAssetPath(textureOrg);
  189. textureIpter = TextureImporter.GetAtPath(impPath) as TextureImporter;
  190. return textureIpter;
  191. }
  192. //写信息到SpritesSheet里
  193. static void WriteMeta(XmlNodeList elemList, string sheetName, Dictionary<string, Vector4> borders)
  194. {
  195. string path = string.Format( "{0}{1}/{2}.png",OutPutDirRoot, sheetName, sheetName);
  196. Texture2D texture = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
  197. string impPath = AssetDatabase.GetAssetPath(texture);
  198. TextureImporter asetImp = TextureImporter.GetAtPath(impPath) as TextureImporter;
  199. SpriteMetaData[] metaData = new SpriteMetaData[elemList.Count];
  200. for ( int i = 0, size = elemList.Count; i < size; i++)
  201. {
  202. XmlElement node = (XmlElement)elemList.Item(i);
  203. Rect rect = new Rect();
  204. rect.x = int.Parse(node.GetAttribute( "x"));
  205. rect.y = texture.height - int.Parse(node.GetAttribute( "y")) - int.Parse(node.GetAttribute( "height"));
  206. rect.width = int.Parse(node.GetAttribute( "width"));
  207. rect.height = int.Parse(node.GetAttribute( "height"));
  208. metaData[i].rect = rect;
  209. metaData[i].pivot = new Vector2( 0.5f, 0.5f);
  210. metaData[i].name = node.GetAttribute( "name");
  211. if (borders.ContainsKey(metaData[i].name))
  212. {
  213. metaData[i].border = borders[metaData[i].name];
  214. }
  215. }
  216. asetImp.spritesheet = metaData;
  217. asetImp.textureType = TextureImporterType.Sprite;
  218. asetImp.spriteImportMode = SpriteImportMode.Multiple;
  219. asetImp.mipmapEnabled = false;
  220. asetImp.SaveAndReimport();
  221. }
  222. }
  223. internal class TextureIpter
  224. {
  225. public string spriteName = "";
  226. public Vector4 border = new Vector4();
  227. public TextureIpter() { }
  228. public TextureIpter(string spriteName, Vector4 border)
  229. {
  230. this.spriteName = spriteName;
  231. this.border = border;
  232. }
  233. }
修改这个类里的常量,可以修改小图目录,输出目录和TexturePacker的安装目录。


怎样使用打出来的图集呢?


 
 
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class Test4 : MonoBehaviour {
  5. // Use this for initialization
  6. void Start ()
  7. {
  8. //resources加载
  9. var sprites = Resources.LoadAll<Sprite>( "Sprites/main/main");
  10. Debug.LogError(sprites[ 0]);
  11. //将图集打包成assetsbundle加载
  12. //加载assetsbundle里的图片,先取得assetbundle再loadall
  13. //var asset = www.assetBundle;
  14. //var sprites = asset.LoadAllAssets(typeof(Sprite));
  15. }
  16. }

点击下载资源点击打开链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值