using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
namespace BFEditor.Resource
{
public class MaterialTools
{
///
/// 删除冗余属性
///
public static void DeleteOverProperty(string matPath)
{
var mat = AssetDatabase.LoadAssetAtPath(matPath);
if (mat != null)
{
var matInfo = new SerializedObject(mat);
var property = matInfo.FindProperty("m_SavedProperties");
property.Next(true);
do
{
if (!property.isArray)
{
continue;
}
for (var i = property.arraySize - 1; i >= 0; --i)
{
var p1 = property.GetArrayElementAtIndex(i);
if (p1.isArray)
{
for (var j = p1.arraySize - 1; j >= 0; --j)
{
var p2 = p1.GetArrayElementAtIndex(j);
var val = p2.FindPropertyRelative("first");
if (!mat.HasProperty(val.stringValue))
{
Debug.Log(matPath + " 删除冗余属性 " + val.stringValue);
p1.DeleteArrayElementAtIndex(j);
}
}
}
else
{
var val = p1.FindPropertyRelative("first");
if (!mat.HasProperty(val.stringValue))
{
Debug.Log(matPath + " 删除冗余属性 " + val.stringValue);
property.DeleteArrayElementAtIndex(i);
}
}
}
}
while (property.Next(false));
matInfo.ApplyModifiedProperties();
}
}
///
/// 删除冗余属性
///
public static void DeleteAllMaterialOverProperty()
{
var guids = AssetDatabase.FindAssets("t:material", new string[] {ResourceProcessConfig.ARTS_FOLDER_PATH });
var total = guids.Length;
var i = 1;
foreach (var guid in guids)
{
var path = AssetDatabase.GUIDToAssetPath(guid);
EditorUtility.DisplayProgressBar("材质检查", path, (float)i / total);
DeleteOverProperty(path);
i++;
}
EditorUtility.ClearProgressBar();
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
///
/// 清理fbx默认材质
///
public static void ClearFbxDefaultMaterial(bool needDialog = false)
{
Debug.Log("[bfinfo]清理fbx默认材质...");
var errorList = new List();
var pathList = BFEditorUtils.GetAssetPathsWithSuffix(ResourceProcessConfig.ARTS_FOLDER_PATH, ".fbx");
var count = 0;
var totalCount = pathList.Count;
foreach (var path in pathList)
{
count++;
EditorUtility.DisplayProgressBar("正在检查清理fbx默认材质", path, (float)count / totalCount);
var obj = AssetDatabase.LoadAssetAtPath(path);
var renderers = obj.GetComponentsInChildren(true);
foreach (var renderer in renderers)
{
foreach (var mat in renderer.sharedMaterials)
{
if (mat != null)
{
Debug.LogError("需要清理默认材质 " + path);
errorList.Add(path);
}
}
}
}
EditorUtility.ClearProgressBar();
foreach (var path in errorList)
{
AssetDatabase.ImportAsset(path); // ModelImporter OnPostprocessModel 清空sharedMaterials
}
if (needDialog)
{
EditorUtility.DisplayDialog("完成", string.Format("共清理{0}个fbx", errorList.Count), "ok");
}
}
}
}