当前位置:   article > 正文

Unity中批量修改图片导入设置及修改图集的设置_unity立绘整合怎么修改

unity立绘整合怎么修改

目的:

一.  导入资源设置

二.   导入时设置图片

三.   设置图集的大小


目的:

一般我们在Unity中使用图片的时候,导入图片的时候都会采取默认设置,如果我们使用Atlas(图集)功能的话,会将好多张图片按照一定大小放到一张图集中去,如果图片多了,有可能图集大小就会过大,然而当当当,在图片的导入设置中有这么一项,MaxSize,这个参数决定了当前图集允许的最大大小,现在碰到这么一个需求,需要修改所有项目中图片的这个设置为固定大小,如果一个个图片去设置,那真的是一个庞大的工作量,这时候强大的度娘就派上用场了,在大量API文档和各种例子中取其精华去其糟粕,获得了一个这样的工具,根据文件夹路径修改所有图片的导入设置为可选配置的值,具体内容就让我们一起来看看吧,啊哈哈。


一.  导入资源设置

首先看看导入设置是个什么鬼,见下图

这时候我们需要修改的参数就是Default中的MaxSize,

 滴滴滴 注意长代码来袭,精华所在。

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using UnityEditor;
  5. using UnityEngine;
  6. public class AtlasSetting : EditorWindow
  7. {
  8. /// <summary>
  9. /// 纹理最大大小
  10. /// </summary>
  11. int m_nTexMaxSize = 1024;
  12. /// <summary>
  13. /// 是否重写其他设置(PC,安卓,IOS)
  14. /// </summary>
  15. bool m_bIsOverride = true;
  16. /// <summary>
  17. /// 默认纹理导入格式
  18. /// </summary>
  19. TextureImporterFormat m_nDefaultPlatformImporterFormat=TextureImporterFormat.Automatic;
  20. /// <summary>
  21. /// 安卓平台纹理导入格式
  22. /// </summary>
  23. TextureImporterFormat m_nAndroidPlatformImporterFormat=TextureImporterFormat.Automatic;
  24. /// <summary>
  25. /// PC纹理导入格式
  26. /// </summary>
  27. TextureImporterFormat m_nPCPlatformImporterFormat=TextureImporterFormat.Automatic;
  28. /// <summary>
  29. /// 苹果纹理导入格式
  30. /// </summary>
  31. TextureImporterFormat m_nIphonePlatformImporterFormat=TextureImporterFormat.Automatic;
  32. /// <summary>
  33. /// 纹理压缩质量
  34. /// </summary>
  35. TextureImporterCompression m_nImporterCompression = TextureImporterCompression.Compressed;
  36. [MenuItem("Tools/AtlasSetting")]
  37. static void ChangeTextureSetting()
  38. {
  39. //创建窗口
  40. Rect window = new Rect(500, 500, 500, 500);
  41. AtlasSetting setting = (AtlasSetting)EditorWindow.GetWindowWithRect(typeof(AtlasSetting), window, false, "AtlasSetting");
  42. setting.Show();
  43. }
  44. private void OnGUI()
  45. {
  46. EditorGUILayout.Space();//空一行
  47. EditorGUILayout.LabelField("修改纹理的设置",new GUIStyle() { alignment=TextAnchor.MiddleCenter, fontSize=16},GUILayout.Height(30));
  48. EditorGUILayout.Space();//空一行
  49. m_nTexMaxSize = int.Parse(EditorGUILayout.TextField("Sprite Max Size","1024"));
  50. EditorGUILayout.Space();//空一行
  51. m_bIsOverride = EditorGUILayout.Toggle("Is Override Other Device",true);
  52. EditorGUILayout.Space();//空一行
  53. m_nDefaultPlatformImporterFormat = (TextureImporterFormat)EditorGUILayout.EnumPopup("Default", m_nDefaultPlatformImporterFormat);
  54. EditorGUILayout.Space();//空一行
  55. m_nPCPlatformImporterFormat = (TextureImporterFormat)EditorGUILayout.EnumPopup(" PC", m_nPCPlatformImporterFormat);
  56. EditorGUILayout.Space();//空一行
  57. m_nAndroidPlatformImporterFormat = (TextureImporterFormat)EditorGUILayout.EnumPopup("Android", m_nAndroidPlatformImporterFormat);
  58. EditorGUILayout.Space();//空一行
  59. m_nIphonePlatformImporterFormat = (TextureImporterFormat)EditorGUILayout.EnumPopup("Iphone", m_nIphonePlatformImporterFormat);
  60. EditorGUILayout.Space();//空一行
  61. if (GUILayout.Button("开始设置", GUILayout.ExpandWidth(true),GUILayout.Height(50)))
  62. {
  63. EditorUtility.DisplayProgressBar("Loading", "in progress", m_fSliderValue);
  64. ChangeAllFileSetting();
  65. }
  66. }
  67. bool m_bIsShowProgressBar = false;
  68. float m_fSliderValue = 0;
  69. /// <summary>
  70. /// 此方法弃用
  71. /// </summary>
  72. static void StartSetting()
  73. {
  74. //var a = Packer.atlasNames;
  75. //var b = Packer.GetTexturesForAtlas(a[0]);
  76. //SpriteAtlas atlas = AssetDatabase.LoadAssetAtPath<SpriteAtlas>(path);
  77. //var c = Packer.GetAlphaTexturesForAtlas(a[1]);
  78. //var d =Packer.
  79. //SpriteAtlasExtensions.GetTextureSettings()
  80. //Debug.Log(a.Length.ToString());
  81. }
  82. /// <summary>
  83. /// 按钮点击的时候开始改变文件设置
  84. /// </summary>
  85. void ChangeAllFileSetting()
  86. {
  87. imageCount = 0;
  88. string filePath = GetSpritePath();
  89. DirectoryInfo dirInfo = new DirectoryInfo(filePath);
  90. CheckDirectory(dirInfo);
  91. var flag = EditorUtility.DisplayDialog("修改完成", $"共修改了{imageCount}个图片", "完成");
  92. EditorUtility.ClearProgressBar();
  93. }
  94. int imageCount = 0;
  95. /// <summary>
  96. /// 这里使用一个迭代函数来处理所有文件夹里面嵌套的文件夹内容
  97. /// </summary>
  98. /// <param name="directoryInfo"></param>
  99. void CheckDirectory(DirectoryInfo directoryInfo)
  100. {
  101. DirectoryInfo[] infos = directoryInfo.GetDirectories();
  102. for (int i = 0,length=infos.Length; i < length; i++)
  103. {
  104. CheckDirectory(infos[i]);
  105. //break;
  106. }
  107. FileInfo[] files = directoryInfo.GetFiles();
  108. ChangeSettingByFolder(files);
  109. }
  110. /// <summary>
  111. /// 改变文件数组中所有文件的设置
  112. /// </summary>
  113. /// <param name="files"></param>
  114. void ChangeSettingByFolder(FileInfo[] files)
  115. {
  116. for (int i = 0, length = files.Length; i < length; i++)
  117. {
  118. if (!files[i].Name.Contains("meta"))
  119. {
  120. string onePath = GetImageProjectPath(files[i].FullName);
  121. TextureImporter m_pImporter = AssetImporter.GetAtPath(onePath) as TextureImporter;
  122. if (m_pImporter == null)
  123. continue;
  124. ChangeTextureSetting(m_pImporter);
  125. imageCount++;
  126. m_fSliderValue = imageCount * 1.0f / 3000;
  127. EditorUtility.DisplayProgressBar("Loading", "in progress", m_fSliderValue);
  128. }
  129. }
  130. }
  131. /// <summary>
  132. /// 根据固定字符串得到资源路径
  133. /// </summary>
  134. /// <param name="fullName"></param>
  135. /// <returns></returns>
  136. string GetImageProjectPath(string fullName)
  137. {
  138. string result = "";
  139. int index = fullName.LastIndexOf("Assets");
  140. result = fullName.Substring(index, fullName.Length- index);
  141. return result;
  142. }
  143. /// <summary>
  144. /// 改变纹理设置
  145. /// </summary>
  146. /// <param name="textureImporter"></param>
  147. void ChangeTextureSetting(TextureImporter textureImporter)
  148. {
  149. if (textureImporter == null)
  150. {
  151. Debug.LogError("获取设置失败");
  152. return;
  153. }
  154. ChangeDefaultSetting(textureImporter);
  155. ChangePCSetting(textureImporter);
  156. ChangeIphoneSetting(textureImporter);
  157. ChangeAndroidSetting(textureImporter);
  158. textureImporter.SaveAndReimport();
  159. }
  160. /// <summary>
  161. /// 修改默认设置
  162. /// </summary>
  163. /// <param name="textureImporter"></param>
  164. void ChangeDefaultSetting(TextureImporter textureImporter)
  165. {
  166. TextureImporterPlatformSettings defaultSetting = textureImporter.GetDefaultPlatformTextureSettings();
  167. defaultSetting.maxTextureSize = m_nTexMaxSize;
  168. //defaultSetting.compressionQuality = defaultSetting.compressionQuality;
  169. defaultSetting.crunchedCompression = false;
  170. defaultSetting.textureCompression = m_nImporterCompression;
  171. defaultSetting.format = m_nDefaultPlatformImporterFormat;
  172. textureImporter.SetPlatformTextureSettings(defaultSetting);
  173. }
  174. /// <summary>
  175. /// 设置所有的设备
  176. /// </summary>
  177. /// <param name="platformSettings"></param>
  178. void SetTextureValue(TextureImporterPlatformSettings platformSettings)
  179. {
  180. platformSettings.maxTextureSize = m_nTexMaxSize;
  181. platformSettings.overridden = m_bIsOverride;
  182. }
  183. /// <summary>
  184. /// 修改PC设置
  185. /// </summary>
  186. /// <param name="textureImporter"></param>
  187. void ChangePCSetting(TextureImporter textureImporter)
  188. {
  189. TextureImporterPlatformSettings pcSetting = textureImporter.GetPlatformTextureSettings("Standalone");
  190. SetTextureValue(pcSetting);
  191. pcSetting.format = m_nPCPlatformImporterFormat;
  192. textureImporter.SetPlatformTextureSettings(pcSetting);
  193. }
  194. /// <summary>
  195. /// 修改安卓设置
  196. /// </summary>
  197. /// <param name="textureImporter"></param>
  198. void ChangeAndroidSetting(TextureImporter textureImporter)
  199. {
  200. TextureImporterPlatformSettings androidSetting = textureImporter.GetPlatformTextureSettings("Android");
  201. SetTextureValue(androidSetting);
  202. androidSetting.format = m_nAndroidPlatformImporterFormat;
  203. textureImporter.SetPlatformTextureSettings(androidSetting);
  204. }
  205. /// <summary>
  206. /// 修改ios设置
  207. /// </summary>
  208. /// <param name="textureImporter"></param>
  209. void ChangeIphoneSetting(TextureImporter textureImporter)
  210. {
  211. TextureImporterPlatformSettings iphoneSetting = textureImporter.GetPlatformTextureSettings("Iphone");
  212. SetTextureValue(iphoneSetting);
  213. iphoneSetting.format = m_nIphonePlatformImporterFormat;
  214. textureImporter.SetPlatformTextureSettings(iphoneSetting);
  215. }
  216. static string GetSpritePath()
  217. {
  218. string streamPath = Application.streamingAssetsPath;
  219. string parentPath=streamPath.Substring(0, streamPath.LastIndexOf('/'));
  220. string resultPath = Path.Combine(parentPath, "自己的文件路径");
  221. return resultPath;
  222. }
  223. }

这里有几点需要注意:

1.        GetPlatformTextureSettings通过这个接口获取的不同平台的设置对应图片中所示的内容设置

 2.        在修改设置值之后需要调用TextureImporter.SaveAndReimport()这个方法来使修改的设置生效,并重新导入。

OK大功告成,需要修改其他参数可以参考官方文档的关于TextureImporter这个类的说明。官方说明

这个导入设置还有上半部分的设置也可以通过脚本修改,但是没有试过,有需要的小伙伴可以自己去摸索摸索,这里提示可以通过TextureImporter.ReadTextureSettings()获取纹理设置,之后修改对应参数,在通过TextureImporter.SetTextureSettings()去使设置生效。具体能否成功,各位看官自行验证吧!!!

二.   导入时设置图片

在导入时设置图片,Unity为我们提供了一个API(AssetPostprocessor),这里面有我们要用的东西。见代码:

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEditor;
  4. using UnityEngine;
  5. public class TextureImporterSetting : AssetPostprocessor
  6. {
  7. //----------------导入设置----------
  8. /// <summary>
  9. /// 纹理最大大小
  10. /// </summary>
  11. int m_nTexMaxSize = 1024;
  12. /// <summary>
  13. /// 是否重写其他设置(PC,安卓,IOS)
  14. /// </summary>
  15. bool m_bIsOverride = true;
  16. /// <summary>
  17. /// 格式
  18. /// </summary>
  19. TextureImporterFormat formatSetting = TextureImporterFormat.Automatic;
  20. /// <summary>
  21. /// 压缩质量
  22. /// </summary>
  23. TextureImporterCompression qualitySetting = TextureImporterCompression.Compressed;
  24. /// <summary>
  25. /// 当一个texture2D在Unity压缩它之前完成导入时,会调用这个函数
  26. /// </summary>
  27. void OnPreprocessTexture()
  28. {
  29. TextureImporter textureImporter=assetImporter as TextureImporter;
  30. if (textureImporter != null)
  31. {
  32. ChangeSpriteSetting(textureImporter);
  33. }
  34. }
  35. void ChangeSpriteSetting(TextureImporter textureImporter)
  36. {
  37. ChangeDefaultSetting(textureImporter);
  38. ChangePCSetting(textureImporter);
  39. ChangeIphoneSetting(textureImporter);
  40. ChangeAndroidSetting(textureImporter);
  41. }
  42. /// <summary>
  43. /// 修改默认设置
  44. /// </summary>
  45. /// <param name="textureImporter"></param>
  46. void ChangeDefaultSetting(TextureImporter textureImporter)
  47. {
  48. TextureImporterPlatformSettings defaultSetting = textureImporter.GetDefaultPlatformTextureSettings();
  49. defaultSetting.maxTextureSize = m_nTexMaxSize;
  50. //defaultSetting.compressionQuality = defaultSetting.compressionQuality;
  51. defaultSetting.crunchedCompression = false;
  52. defaultSetting.textureCompression = qualitySetting;
  53. defaultSetting.format = formatSetting;
  54. textureImporter.SetPlatformTextureSettings(defaultSetting);
  55. }
  56. /// <summary>
  57. /// 设置所有的设备
  58. /// </summary>
  59. /// <param name="platformSettings"></param>
  60. void SetTextureValue(TextureImporterPlatformSettings platformSettings)
  61. {
  62. platformSettings.maxTextureSize = m_nTexMaxSize;
  63. platformSettings.overridden = m_bIsOverride;
  64. }
  65. /// <summary>
  66. /// 修改PC设置
  67. /// </summary>
  68. /// <param name="textureImporter"></param>
  69. void ChangePCSetting(TextureImporter textureImporter)
  70. {
  71. TextureImporterPlatformSettings pcSetting = textureImporter.GetPlatformTextureSettings("Standalone");
  72. SetTextureValue(pcSetting);
  73. pcSetting.format = formatSetting;
  74. textureImporter.SetPlatformTextureSettings(pcSetting);
  75. }
  76. /// <summary>
  77. /// 修改安卓设置
  78. /// </summary>
  79. /// <param name="textureImporter"></param>
  80. void ChangeAndroidSetting(TextureImporter textureImporter)
  81. {
  82. TextureImporterPlatformSettings androidSetting = textureImporter.GetPlatformTextureSettings("Android");
  83. SetTextureValue(androidSetting);
  84. androidSetting.format = formatSetting;
  85. textureImporter.SetPlatformTextureSettings(androidSetting);
  86. }
  87. /// <summary>
  88. /// 修改ios设置
  89. /// </summary>
  90. /// <param name="textureImporter"></param>
  91. void ChangeIphoneSetting(TextureImporter textureImporter)
  92. {
  93. TextureImporterPlatformSettings iphoneSetting = textureImporter.GetPlatformTextureSettings("Iphone");
  94. SetTextureValue(iphoneSetting);
  95. iphoneSetting.format = formatSetting;
  96. textureImporter.SetPlatformTextureSettings(iphoneSetting);
  97. }
  98. }

三.   设置图集的大小

以上修改了图片的设置,但是在项目中我们往往还会碰到修改图集的需求,尤其在后期项目做优化的时候,对图集的管理就更加至关重要了,后来发现雨松的一篇文章对此进行实现,在这里也分享一下,同时自己也记录一下,后面用到方便。o(* ̄▽ ̄*)ブ

  1. using System;
  2. using System.Linq;
  3. using UnityEngine;
  4. using UnityEditor;
  5. using UnityEditor.Sprites;
  6. using System.Collections.Generic;
  7. // DefaultPackerPolicy will pack rectangles no matter what Sprite mesh type is unless their packing tag contains "[TIGHT]".
  8. class CustomAtlasPolicy : UnityEditor.Sprites.IPackerPolicy
  9. {
  10. protected class Entry
  11. {
  12. public Sprite sprite;
  13. public AtlasSettings settings;
  14. public string atlasName;
  15. public SpritePackingMode packingMode;
  16. }
  17. public virtual int GetVersion() { return 1; }
  18. protected virtual string TagPrefix { get { return "[TIGHT]"; } }
  19. protected virtual bool AllowTightWhenTagged { get { return true; } }
  20. public bool AllowSequentialPacking => true;
  21. public void OnGroupAtlases(BuildTarget target, PackerJob job, int[] textureImporterInstanceIDs)
  22. {
  23. List<Entry> entries = new List<Entry>();
  24. foreach (int instanceID in textureImporterInstanceIDs)
  25. {
  26. TextureImporter ti = EditorUtility.InstanceIDToObject(instanceID) as TextureImporter;
  27. TextureFormat desiredFormat;
  28. ColorSpace colorSpace;
  29. int compressionQuality;
  30. ti.ReadTextureImportInstructions(target, out desiredFormat, out colorSpace, out compressionQuality);
  31. TextureImporterSettings tis = new TextureImporterSettings();
  32. ti.ReadTextureSettings(tis);
  33. Sprite[] sprites = AssetDatabase.LoadAllAssetRepresentationsAtPath(ti.assetPath).Select(x => x as Sprite).Where(x => x != null).ToArray();
  34. foreach (Sprite sprite in sprites)
  35. {
  36. //在这里设置每个图集的参数
  37. Entry entry = new Entry();
  38. entry.sprite = sprite;
  39. entry.settings.format = desiredFormat;
  40. //entry.settings.usageMode = ins.usageMode;
  41. entry.settings.colorSpace = colorSpace;
  42. entry.settings.compressionQuality = compressionQuality;
  43. entry.settings.filterMode = Enum.IsDefined(typeof(FilterMode), ti.filterMode) ? ti.filterMode : FilterMode.Bilinear;
  44. entry.settings.maxWidth = 1024;
  45. entry.settings.maxHeight = 1024;
  46. entry.atlasName = ParseAtlasName(ti.spritePackingTag);
  47. entry.packingMode = GetPackingMode(ti.spritePackingTag, tis.spriteMeshType);
  48. entries.Add(entry);
  49. }
  50. Resources.UnloadAsset(ti);
  51. }
  52. // First split sprites into groups based on atlas name
  53. var atlasGroups =
  54. from e in entries
  55. group e by e.atlasName;
  56. foreach (var atlasGroup in atlasGroups)
  57. {
  58. int page = 0;
  59. // Then split those groups into smaller groups based on texture settings
  60. var settingsGroups =
  61. from t in atlasGroup
  62. group t by t.settings;
  63. foreach (var settingsGroup in settingsGroups)
  64. {
  65. string atlasName = atlasGroup.Key;
  66. if (settingsGroups.Count() > 1)
  67. atlasName += string.Format(" (Group {0})", page);
  68. job.AddAtlas(atlasName, settingsGroup.Key);
  69. foreach (Entry entry in settingsGroup)
  70. {
  71. job.AssignToAtlas(atlasName, entry.sprite, entry.packingMode, SpritePackingRotation.None);
  72. }
  73. ++page;
  74. }
  75. }
  76. }
  77. protected bool IsTagPrefixed(string packingTag)
  78. {
  79. packingTag = packingTag.Trim();
  80. if (packingTag.Length < TagPrefix.Length)
  81. return false;
  82. return (packingTag.Substring(0, TagPrefix.Length) == TagPrefix);
  83. }
  84. private string ParseAtlasName(string packingTag)
  85. {
  86. string name = packingTag.Trim();
  87. if (IsTagPrefixed(name))
  88. name = name.Substring(TagPrefix.Length).Trim();
  89. return (name.Length == 0) ? "(unnamed)" : name;
  90. }
  91. private SpritePackingMode GetPackingMode(string packingTag, SpriteMeshType meshType)
  92. {
  93. if (meshType == SpriteMeshType.Tight)
  94. if (IsTagPrefixed(packingTag) == AllowTightWhenTagged)
  95. return SpritePackingMode.Tight;
  96. return SpritePackingMode.Rectangle;
  97. }
  98. }

此脚本转载于雨松博客,地址:雨松博客

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/125565
推荐阅读
相关标签
  

闽ICP备14008679号