unity怎么对图片资源批处理
时间: 2024-03-13 09:42:56 浏览: 21
在Unity中,你可以使用Editor Script来对图片资源进行批处理。以下是一些简单的示例。
1. 批量修改图片格式
你可以使用以下代码将所有选定的图片转换为PNG格式:
```csharp
using UnityEditor;
using UnityEngine;
using System.IO;
public class BatchImageFormat : EditorWindow {
[MenuItem("Tools/Batch Image Format Converter/Convert to PNG")]
static void ConvertToPNG() {
foreach (Object obj in Selection.objects) {
string assetPath = AssetDatabase.GetAssetPath(obj);
TextureImporter textureImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter;
textureImporter.textureCompression = TextureImporterCompression.Uncompressed;
textureImporter.SaveAndReimport();
Texture2D texture = AssetDatabase.LoadAssetAtPath<Texture2D>(assetPath);
byte[] bytes = texture.EncodeToPNG();
File.WriteAllBytes(assetPath, bytes);
}
}
}
```
2. 批量修改图片尺寸
你可以使用以下代码将所有选定的图片的尺寸修改为指定的宽度和高度:
```csharp
using UnityEditor;
using UnityEngine;
using System.IO;
public class BatchImageResize : EditorWindow {
int newWidth = 512;
int newHeight = 512;
[MenuItem("Tools/Batch Image Resizer/Resize Images")]
static void Init() {
BatchImageResize window = EditorWindow.GetWindow<BatchImageResize>();
window.Show();
}
void OnGUI() {
EditorGUILayout.LabelField("New Size");
newWidth = EditorGUILayout.IntField("Width", newWidth);
newHeight = EditorGUILayout.IntField("Height", newHeight);
if (GUILayout.Button("Resize")) {
foreach (Object obj in Selection.objects) {
string assetPath = AssetDatabase.GetAssetPath(obj);
TextureImporter textureImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter;
textureImporter.isReadable = true;
textureImporter.SaveAndReimport();
Texture2D texture = AssetDatabase.LoadAssetAtPath<Texture2D>(assetPath);
TextureScale.Bilinear(texture, newWidth, newHeight);
byte[] bytes = texture.EncodeToPNG();
File.WriteAllBytes(assetPath, bytes);
}
}
}
}
```
这里使用了一个名为`TextureScale.Bilinear`的方法来修改纹理的大小。这个方法可以在Unity的官方论坛上找到。