多选材质球,执行DDSToPNG.DdsToPng()
using System.IO;
using UnityEditor;
using UnityEngine;
public class DDSToPNG : Editor
{
[MenuItem("Tools/DdsToPng", false, 100)]
public static void DdsToPng()
{
foreach (var obj in Selection.objects)
{
if (obj.GetType() == typeof(Material))
{
Material _mat = (Material)obj;
Shader shader = _mat.shader;
// 遍历Shader的所有属性
for (int i = 0; i < ShaderUtil.GetPropertyCount(shader); ++i)
{
// 只对Texture类型属性执行
if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.TexEnv)
{
// 获取属性名
string propertyName = ShaderUtil.GetPropertyName(shader, i);
// 获取属性对应的贴图
Texture tex = _mat.GetTexture(propertyName);
if (tex == null)
continue;
string texPath = AssetDatabase.GetAssetPath(tex.GetInstanceID());
if (texPath.EndsWith(".dds"))
{
Debug.Log(texPath);
string pngTex = texPath.Replace("dds", "png");
// 保存PNG图片
File.WriteAllBytes(System.Environment.CurrentDirectory + "/" + pngTex, DeCompress(tex).EncodeToPNG());
// 导入PNG资源
AssetDatabase.ImportAsset(pngTex);
// 重新给材质球设置贴图
_mat.SetTexture(propertyName, AssetDatabase.LoadAssetAtPath<Texture>(pngTex));
}
}
}
}
}
AssetDatabase.Refresh();
}
/// <summary>
/// 将Texture解压到Texture2D
/// 解决部分Texture2D转换错误
/// </summary>
/// <param name="source"></param>
/// <returns>byte[]</returns>
public static Texture2D DeCompress(Texture source)
{
if (source == null)
{
return null;
}
RenderTexture renderTex = RenderTexture.GetTemporary(
source.width,
source.height,
0,
RenderTextureFormat.Default,
RenderTextureReadWrite.Linear);
Graphics.Blit(source, renderTex);
RenderTexture previous = RenderTexture.active;
RenderTexture.active = renderTex;
Texture2D readableText = new Texture2D(source.width, source.height);
readableText.ReadPixels(new Rect(0, 0, renderTex.width, renderTex.height), 0, 0);
readableText.Apply();
RenderTexture.active = previous;
RenderTexture.ReleaseTemporary(renderTex);
return readableText;
}
}