【工具】增加自动替换UI材质工具

main
刘涛 2025-09-16 13:50:51 +08:00
parent cb0f4fc69d
commit d91e1830d8
1 changed files with 63 additions and 22 deletions

View File

@ -21,28 +21,18 @@ namespace GameEditor.UIMaterialReplacer
private static bool HasTransparency(Texture2D texture) private static bool HasTransparency(Texture2D texture)
{ {
// 方法1: 检查纹理格式
var format = texture.format;
bool formatSupportsAlpha = format == TextureFormat.RGBA32 ||
format == TextureFormat.ARGB32 ||
format == TextureFormat.RGBA4444 ||
format == TextureFormat.ARGB4444 ||
format == TextureFormat.Alpha8 ||
format == TextureFormat.ETC2_RGBA8 ||
format == TextureFormat.DXT5 ||
format == TextureFormat.BC7;
if (!formatSupportsAlpha) return false;
// 方法2: 检查像素数据(需要纹理可读) // 方法2: 检查像素数据(需要纹理可读)
if (!texture.isReadable) return true; if (!texture.isReadable)
{
return HasTransparencyFromFile(texture);
}
try try
{ {
var pixels = texture.GetPixels32(); var pixels = texture.GetPixels32();
foreach (var pixel in pixels) foreach (var pixel in pixels)
{ {
if (pixel.a < 255) // 发现非完全不透明的像素 if (pixel.a < 255 && pixel.a > 0) // 发现非完全不透明的像素
{ {
return true; return true;
} }
@ -56,6 +46,57 @@ namespace GameEditor.UIMaterialReplacer
} }
} }
private static bool HasTransparencyFromFile(Texture2D texture)
{
string assetPath = AssetDatabase.GetAssetPath(texture);
if (string.IsNullOrEmpty(assetPath))
{
return true; // 无法获取路径保守返回true
}
try
{
// 使用Unity的ImageConversion加载原始图片数据
byte[] fileBytes = System.IO.File.ReadAllBytes(assetPath);
// 创建临时纹理来加载数据
Texture2D tempTexture = new Texture2D(2, 2);
if (tempTexture.LoadImage(fileBytes))
{
// 检查加载后的像素数据
try
{
var pixels = tempTexture.GetPixels32();
foreach (var pixel in pixels)
{
if (pixel.a < 255 && pixel.a > 0) // 发现非完全不透明的像素
{
Object.DestroyImmediate(tempTexture);
return true;
}
}
Object.DestroyImmediate(tempTexture);
return false;
}
catch
{
Object.DestroyImmediate(tempTexture);
return true;
}
}
else
{
Object.DestroyImmediate(tempTexture);
return true; // 无法加载保守返回true
}
}
catch (System.Exception e)
{
Debug.LogWarning($"通过IO检查透明信息失败 {assetPath}: {e.Message}");
return true; // 出错时保守返回true
}
}
private static void _TryReplace(GameObject go) private static void _TryReplace(GameObject go)
{ {
// 替换材质 // 替换材质