环境
Unity5.6.0f3
在U3D中,材质球的属性是跟随shader属性保存到材质球的SaveProperties中,但是切换shader的时候,旧的属性并不会被删掉,虽然这些属性在打包的时候会被过滤掉,但是这会影响到编辑器下对材质球的一些编辑操作。
static void ClearMaterialUnusedProperties(Material mat, bool isSaveImmediate = true)
{
SerializedObject matInfo = new SerializedObject(mat);
SerializedProperty propArr = matInfo.FindProperty("m_SavedProperties");
propArr.Next(true);
do
{
if (!propArr.isArray) continue;
for (int i = propArr.arraySize - 1; i >= 0; --i)
{
var p1 = propArr.GetArrayElementAtIndex(i);
if (p1.isArray)
{
for (int ii = p1.arraySize - 1; ii >= 0; --ii)
{
var p2 = p1.GetArrayElementAtIndex(ii);
var val = p2.FindPropertyRelative("first");
if (!mat.HasProperty(val.stringValue))
{
Debug.Log("remove " + mat.name + "," + val.stringValue);
p1.DeleteArrayElementAtIndex(ii);
}
}
}
else
{
var val = p1.FindPropertyRelative("first");
if (!mat.HasProperty(val.stringValue))
{
Debug.Log("remove " + mat.name + "," + val.stringValue);
propArr.DeleteArrayElementAtIndex(i);
}
}
}
} while (propArr.Next(false));
matInfo.ApplyModifiedProperties();
//Resources.UnloadAsset(mat);
if (isSaveImmediate)
AssetDatabase.SaveAssets();
}