说明
最近美术同事在整理模型动画时有一个需求,就是选中部分的模型一件将材质替换成同一个材质球。在编辑器下将这个功能实现了出来。代码放在最后,简单记录一下。文章来源:https://www.toymoban.com/news/detail-544805.html
思路
- 首先对选中进行遍历,拿到所有的子对象;
- 对每个具体的对象拿到对应的
Mesh Renderer
组件; - 对每个
MeshRender
组件中的Materials
进行判断,判断是否有材质,材质是否有多个的情况; - 在替换成功后支持回退的功能;
效果
这里是在Transform组件中调出对应的方法,因为有可能选中的物体没有MeshRenderer
组件。支持选中多个物体。
文章来源地址https://www.toymoban.com/news/detail-544805.html
代码
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class HK_ReplaceMaterial : Editor
{
[MenuItem("CONTEXT/Transform/ReplaceMaterial")]
static void MaterialReplacing()
{
MaterialReplacingEditorPanel.ShowReplaceMaterials();
}
}
public class MaterialReplacingEditorPanel : EditorWindow
{
//要替换的材质
Material _material;
public static void ShowReplaceMaterials()
{
EditorWindow ReplaceMaterialsWindow = GetWindow<MaterialReplacingEditorPanel>("ReplaceMaterials");
ReplaceMaterialsWindow.Show();
}
private void OnGUI()
{
GUILayout.Space(10);
GUILayout.BeginHorizontal();
GUILayout.Label("材质替换", GUILayout.Width(100f));
_material = EditorGUILayout.ObjectField(_material, typeof(Material), true) as Material;
GUILayout.EndHorizontal();
GUILayout.Space(10);
if (GUILayout.Button("替换"))
{
var selectionObjs = Selection.gameObjects;
if (_material == null)
{
EditorUtility.DisplayDialog("提醒", string.Format("当前没有选择任何材质"), "确定");
}
else if (selectionObjs.Length == 0)
{
EditorUtility.DisplayDialog("提醒", string.Format("当前没有选中物体"), "确定");
}
else if (EditorUtility.DisplayDialog("提醒", string.Format("是否将当前选中的物体全部替换材质?", _material.name), "确定", "取消"))
{
for (int i = 0; i < selectionObjs.Length; i++)
{
TraverseChild(selectionObjs[i]);
}
}
}
}
void TraverseChild(GameObject thisObject)
{
//回退
List<Object> obj = new List<Object>();
for (int i = 0; i < thisObject.GetComponentsInChildren<Renderer>(true).Length; i++)
{
if (thisObject == null)
continue;
else if (thisObject.GetComponentsInChildren<Renderer>(true)[i] == null)
continue;
else if (thisObject.GetComponentsInChildren<Renderer>(true)[i].sharedMaterial == null)
continue;
obj.Add(thisObject.GetComponentsInChildren<Renderer>(true)[i]);
}
Undo.RecordObjects(obj.ToArray(), "ds");
for (int i = 0; i < thisObject.GetComponentsInChildren<Renderer>(true).Length; i++)
{
if (thisObject == null)
continue;
else if (thisObject.GetComponentsInChildren<Renderer>(true)[i] == null)
continue;
else if (thisObject.GetComponentsInChildren<Renderer>(true)[i].sharedMaterial == null)
continue;
List<Material> materials = new List<Material>();
foreach (var j in thisObject.GetComponentsInChildren<Renderer>(true)[i].sharedMaterials)
{
materials.Add(_material);
}
thisObject.GetComponentsInChildren<Renderer>(true)[i].sharedMaterials = materials.ToArray();
}
}
}
到了这里,关于Unity编辑器实现对选中物体一键替换材质的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!