ResCompression.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using UnityEditor;
  2. using UnityEngine;
  3. public static class ResCompression
  4. {
  5. [MenuItem("Tools/Res Compre")]
  6. public static void ResCompres()
  7. {
  8. CompreImages();
  9. }
  10. private static void CompreImages()
  11. {
  12. string[] textureGuids = AssetDatabase.FindAssets("t:Texture2D", new[] { "Assets" });
  13. int changedCount = 0;
  14. try
  15. {
  16. for (int i = 0; i < textureGuids.Length; i++)
  17. {
  18. string assetPath = AssetDatabase.GUIDToAssetPath(textureGuids[i]);
  19. EditorUtility.DisplayProgressBar(
  20. "Compress Images",
  21. assetPath,
  22. textureGuids.Length == 0 ? 1f : (float)i / textureGuids.Length);
  23. TextureImporter importer = AssetImporter.GetAtPath(assetPath) as TextureImporter;
  24. if (importer == null)
  25. {
  26. continue;
  27. }
  28. importer.GetSourceTextureWidthAndHeight(out int width, out int height);
  29. int maxSize = GetLowerPowerOfTwoMaxSize(Mathf.Max(width, height));
  30. bool changed = false;
  31. if (importer.mipmapEnabled)
  32. {
  33. importer.mipmapEnabled = false;
  34. changed = true;
  35. }
  36. TextureImporterPlatformSettings iosSettings =
  37. importer.GetPlatformTextureSettings("iPhone");
  38. if (!iosSettings.overridden ||
  39. iosSettings.format != TextureImporterFormat.ASTC_6x6 ||
  40. iosSettings.maxTextureSize != maxSize)
  41. {
  42. iosSettings.name = "iPhone";
  43. iosSettings.overridden = true;
  44. iosSettings.format = TextureImporterFormat.ASTC_6x6;
  45. iosSettings.maxTextureSize = maxSize;
  46. importer.SetPlatformTextureSettings(iosSettings);
  47. changed = true;
  48. }
  49. if (changed)
  50. {
  51. importer.SaveAndReimport();
  52. changedCount++;
  53. }
  54. }
  55. }
  56. finally
  57. {
  58. EditorUtility.ClearProgressBar();
  59. }
  60. Debug.Log($"Image compression completed. Scanned {textureGuids.Length} textures, " +
  61. $"updated {changedCount} textures.");
  62. }
  63. private static int GetLowerPowerOfTwoMaxSize(int sourceSize)
  64. {
  65. const int minSize = 32;
  66. const int maxSize = 1024;
  67. if (sourceSize <= minSize)
  68. {
  69. return minSize;
  70. }
  71. int size = minSize;
  72. while (size <= maxSize / 2 && size * 2 <= sourceSize)
  73. {
  74. size *= 2;
  75. }
  76. return size;
  77. }
  78. }