Unity实战(11):项目非启动状态下使用代码批量替换材质

目录

前言

配置环境

一、场景准备

二、代码演示

三、效果呈现

四、关于Resources.Load()的说明


前言

本文内容为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<Renderer>(targetModel, (Renderer r) => {
            Material mat = Resources.Load<Material>("Materials/mod_06_lightmap 1") as Material;
            //r.material = mat;
            Debug.Log(mat);
            targetModel.GetComponent<MeshRenderer>().material = mat;
        });
    }
    // 遍历获取所有子物体
    public static void GetGOAllChilren<W>(GameObject go, Action<W> a) {
        if (go.transform.childCount > 0) {
            for (int i = 0; i < go.transform.childCount; i++) {
                GameObject g = go.transform.GetChild(i).gameObject;
                GetGOAllChilren<W>(g, a);
            }
        }

        if (go.TryGetComponent<W>(out W w)) {
            a?.Invoke(w);
        };
    }
}

 保存后可以看到unity中多了一栏

三、效果呈现

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

替换前:

替换后:

 这样便在不启动项目的前提下替换了物体的材质。

批量替换材质只需要修改上述代码即可。

四、关于Resources.Load()的说明

这个方法加载本地文件时需要在Assets下新建一个Resources的文件夹,路径“Materials/mod_06_lightmap 1”是在Resources下Materials下面的mod_09_lightmap 1.mat文件,在写路径的时候不要加上文件的后缀。

猜你喜欢

转载自blog.csdn.net/qq_41904236/article/details/133104653