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


    目录

    前言

    配置环境

    一、场景准备

    二、代码演示

    三、效果呈现

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


    前言

    本文内容为unity在编辑状态(非启动状态)下使用代码批量替换材质,该方法也适用于其他在编辑状态下对物体的操作需求。

    配置环境

    win10

    unity2021.2.13f1

    visual studio2022

    一、场景准备

    在建模软件中做一个场景并导入unity如下

    现在的目标是在不启动项目的情况下,将场景中的物体批量替换材质 

    二、代码演示

    替换单个物体材质

    在Assets下新建一个文件夹名为Editor,在这个文件夹下新建一个脚本名为ChangeModelMaterials.cs,需要注意的是该类继承自Editor。这个Editor文件夹下的脚本不参与项目编译

    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEditor;
    5. using UnityEngine;
    6. public class ChangeModelMaterils : Editor {
    7. public static GameObject targetModel;
    8. public static Material srcTargett;
    9. //创建多级菜单并声明顺序
    10. [MenuItem("自定义工具/材质替换", false, 100)]
    11. public static void Menu1() {
    12. // 获取场景中的物体
    13. targetModel = GameObject.Find("mod_06");
    14. // 遍历处理的静态方法,当遍历到一个子物体后就会触发相应的处理事件,此处的事件是替换指定的材质
    15. GetGOAllChilren(targetModel, (Renderer r) => {
    16. Material mat = Resources.Load("Materials/mod_06_lightmap 1") as Material;
    17. //r.material = mat;
    18. Debug.Log(mat);
    19. targetModel.GetComponent().material = mat;
    20. });
    21. }
    22. // 遍历获取所有子物体
    23. public static void GetGOAllChilren<W>(GameObject go, Action a) {
    24. if (go.transform.childCount > 0) {
    25. for (int i = 0; i < go.transform.childCount; i++) {
    26. GameObject g = go.transform.GetChild(i).gameObject;
    27. GetGOAllChilren(g, a);
    28. }
    29. }
    30. if (go.TryGetComponent(out W w)) {
    31. a?.Invoke(w);
    32. };
    33. }
    34. }

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

    三、效果呈现

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

    替换前:

    替换后:

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

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

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

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

  • 相关阅读:
    博客程序系统其它功能扩充
    [开发] java日期操作
    TCP粘包问题解决方案
    JS狂神说
    聊聊 Kubectl scale 命令的优秀实践
    【Android 从入门到出门】第一章:Android开发技能入门指南
    Spring Boot面试题
    借教室——二分、前缀和、差分
    Gradle 笔记
    C++面向对象语言自制多级菜单
  • 原文地址:https://blog.csdn.net/qq_41904236/article/details/133104653