先看效果
实现方案
1:创建几个用于测试的Cube
2:创建一个脚本
3:编写脚本内容
主要是这部分的逻辑
附上完整代码
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class Tool
{
[MenuItem("TOOL/ReplaceMaterial")]
public static void Open()
{
var window = EditorWindow.GetWindow(typeof(ReplaceMA));
window.title = "材质球替换工具";
}
}
public class ReplaceMA : EditorWindow
{
private GameObject _GameObject;
private Material _Material;
private void OnGUI()
{
if (!Application.isPlaying)
{
GUILayout.Label("拖入一个你想替换材质球的游戏物体");
_GameObject = (GameObject)EditorGUILayout.ObjectField(_GameObject, typeof(GameObject), true);
GUILayout.Label("拖入一个你想替换的材质球");
_Material = (Material)EditorGUILayout.ObjectField(_Material, typeof(Material), true);
if (GUILayout.Button("点击替换"))
{
if (_GameObject == null || _Material == null)
{
Debug.LogError("你要替换材质的游戏物体或者材质球为空");
return;
}
var RenderList = new List<Renderer>();
RenderList.Add(_GameObject.gameObject.GetComponent<Renderer>());
RenderList.AddRange(_GameObject.GetComponentsInChildren<Renderer>());
Undo.RecordObjects(RenderList.ToArray(), "Replace");//这句话非常重要,不然得气死个人!!!
foreach (var item in RenderList)
{
var materials = item.sharedMaterials;
for (int i = 0; i < materials.Length; i++)
{
materials[i] = _Material;
}
item.sharedMaterials = materials;
}
}
}
}
}
4,然后就完成啦,同样你也可以按照我的思路再扩展扩展,可以替换你自己想要的内容