106 lines
3.4 KiB
C#
106 lines
3.4 KiB
C#
using UnityEditor;
|
|
using UnityEngine;
|
|
namespace GameEditor.UIMaterialReplacer
|
|
{
|
|
public class UIReplacer
|
|
{
|
|
|
|
private static string _matPath = "Assets/Art_Out/UI/Material/gama_mat.mat";
|
|
|
|
[MenuItem("Assets/Editor/UIMaterialReplacer/Replace UI Material")]
|
|
[MenuItem("GameObject/Editor/UIMaterialReplacer/Replace UI Material", false, 10)]
|
|
public static void ReplaceUI()
|
|
{
|
|
// 获取选中的所有GameObject
|
|
var selectedObjects = Selection.GetFiltered<UnityEngine.GameObject>(SelectionMode.DeepAssets);
|
|
foreach (var selectedObject in selectedObjects)
|
|
{
|
|
_TryReplace(selectedObject);
|
|
}
|
|
}
|
|
|
|
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: 检查像素数据(需要纹理可读)
|
|
if (!texture.isReadable) return true;
|
|
|
|
try
|
|
{
|
|
var pixels = texture.GetPixels32();
|
|
foreach (var pixel in pixels)
|
|
{
|
|
if (pixel.a < 255) // 发现非完全不透明的像素
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
catch
|
|
{
|
|
// 无法读取像素数据,回退到格式检查
|
|
return true;
|
|
}
|
|
}
|
|
|
|
private static void _TryReplace(GameObject go)
|
|
{
|
|
// 替换材质
|
|
var loadMat = AssetDatabase.LoadAssetAtPath<Material>(_matPath);
|
|
if (loadMat == null)
|
|
{
|
|
Debug.LogError("加载材质失败: " + _matPath);
|
|
return;
|
|
}
|
|
|
|
Debug.Log($"开始处理 {go.name}");
|
|
var isModify = false;
|
|
var allImages = go.GetComponentsInChildren<UnityEngine.UI.Image>(true);
|
|
foreach (var img in allImages)
|
|
{
|
|
if (img.sprite == null)
|
|
{
|
|
continue;
|
|
}
|
|
// 判断sprite是否包含透明信息
|
|
var texture = img.sprite.texture;
|
|
if (texture == null)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (!HasTransparency(texture))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
img.material = loadMat;
|
|
Debug.Log($"替换材质: {img.gameObject.name} 贴图: {texture.name}");
|
|
isModify = true;
|
|
}
|
|
|
|
if (isModify)
|
|
{
|
|
EditorUtility.SetDirty(go);
|
|
AssetDatabase.SaveAssets();
|
|
}
|
|
|
|
Debug.Log($"处理完成 {go.name}");
|
|
}
|
|
|
|
}
|
|
}
|