ExportPreviewTools
介绍
导出Unity资源的预览缩略图
使用场景
在某些情况下想要展示拥有的模型资源进行预览时,可以使用其快速预览功能。
工具原理
- Selection类
//获取选中的资源的GUID
string[] assetGUIDs = Selection.assetGUIDs;
- AssetDatabase类操作资源
//获取预制体
string assetPath = AssetDatabase.GUIDToAssetPath(assetGUID);
Object asset = AssetDatabase.LoadAssetAtPath<Object>(assetPath);
- AssetPreview生成和获取资源的预览图像
Texture2D previewTexture = AssetPreview.GetAssetPreview(asset);
- IO写入文件
if (!System.IO.Directory.Exists(folderPath))
{System.IO.Directory.CreateDirectory(folderPath);
}System.IO.File.WriteAllBytes(exportPath, pngData);
- EncodeToPNG Texture2D 转化为 PNG 字节数组
byte[] pngData = previewTexture.EncodeToPNG();
代码
using UnityEditor;
using UnityEngine;public static class ExportPreviewTool
{[MenuItem("Tools/Export Preview Images")]static void ExportImages(){//获取当前选中资产的GUIDsstring[] assetGUIDs = Selection.assetGUIDs;foreach (string assetGUID in assetGUIDs){// 获取资产Texture2Dstring assetPath = AssetDatabase.GUIDToAssetPath(assetGUID);Object asset = AssetDatabase.LoadAssetAtPath<Object>(assetPath);Texture2D previewTexture = AssetPreview.GetAssetPreview(asset);//导出Png图片if (previewTexture != null){string folderPath = "Assets/ExportedPreviews";string exportPath = $"{folderPath}/{asset.name}.png";if (!System.IO.Directory.Exists(folderPath)){System.IO.Directory.CreateDirectory(folderPath);}// Texture2D 转化为 PNG 字节数组byte[] pngData = previewTexture.EncodeToPNG();System.IO.File.WriteAllBytes(exportPath, pngData);Debug.Log("Exported preview image to: " + exportPath);}else{Debug.LogWarning("No preview image available for: " + assetPath);}}}
}