目录
本文内容为unity在编辑状态(非启动状态)下使用代码批量替换材质,该方法也适用于其他在编辑状态下对物体的操作需求。
win10
unity2021.2.13f1
visual studio2022
在建模软件中做一个场景并导入unity如下

现在的目标是在不启动项目的情况下,将场景中的物体批量替换材质
替换单个物体材质
在Assets下新建一个文件夹名为Editor,在这个文件夹下新建一个脚本名为ChangeModelMaterials.cs,需要注意的是该类继承自Editor。这个Editor文件夹下的脚本不参与项目编译

- using System;
- using System.Collections;
- using System.Collections.Generic;
- using UnityEditor;
- using UnityEngine;
-
-
- public class ChangeModelMaterils : Editor {
- public static GameObject targetModel;
- public static Material srcTargett;
- //创建多级菜单并声明顺序
- [MenuItem("自定义工具/材质替换", false, 100)]
- public static void Menu1() {
- // 获取场景中的物体
- targetModel = GameObject.Find("mod_06");
- // 遍历处理的静态方法,当遍历到一个子物体后就会触发相应的处理事件,此处的事件是替换指定的材质
- GetGOAllChilren
(targetModel, (Renderer r) => { - Material mat = Resources.Load
("Materials/mod_06_lightmap 1") as Material; - //r.material = mat;
- Debug.Log(mat);
- targetModel.GetComponent
().material = mat; - });
- }
- // 遍历获取所有子物体
- public static void GetGOAllChilren<W>(GameObject go, Action
a ) { - if (go.transform.childCount > 0) {
- for (int i = 0; i < go.transform.childCount; i++) {
- GameObject g = go.transform.GetChild(i).gameObject;
- GetGOAllChilren
(g, a); - }
- }
-
- if (go.TryGetComponent
(out W w)) { - a?.Invoke(w);
- };
- }
- }
-
保存后可以看到unity中多了一栏

当点击工具时便会执行上述代码中的Menu1方法,这里选择替换材质的模型是mod_06(茶壶),会将其材质替换为mod_06_lightmap 1
替换前:

替换后:
这样便在不启动项目的前提下替换了物体的材质。
批量替换材质只需要修改上述代码即可。
这个方法加载本地文件时需要在Assets下新建一个Resources的文件夹,路径“Materials/mod_06_lightmap 1”是在Resources下Materials下面的mod_09_lightmap 1.mat文件,在写路径的时候不要加上文件的后缀。