Unity 编辑器开发实战【Model Importer】- 如何多选设置模型导入设置中的Material Location

2022-08-29 16:51:08 浏览数 (1)

模型的Import Settings中Materials部分是不支持多选进行编辑的,如图所示,如果我们选中多个模型,编辑器中会提示Material Editing is not supported on multiple selection.

假如我们往工程中导入了大量模型,其默认的Location设置为Use Embedded Materials,而我们想要将其设为Use External Materials(Legacy),就需要依次选中模型、设置Location,比较耗时耗力。

本文实现的工具可以支持多选模型进行Material Location设置,如图所示:

代码如下:

代码语言:javascript复制
using UnityEngine;
using UnityEditor;

namespace SK.Framework
{
    public class ModelImportSettings : EditorWindow
    {
        //Location类型
        private ModelImporterMaterialLocation location;
        //菜单
        [MenuItem("SKFramework/Tools/Model Import Settings")]
        private static void Open()
        {
            GetWindow<ModelImportSettings>("Model Import Settings").Show();
        }

        private void OnGUI()
        {
            //水平布局
            GUILayout.BeginHorizontal();
            {
                GUILayout.Label("Location");
                //EnumPopup显示选择的Location类型
                location = (ModelImporterMaterialLocation)EditorGUILayout.EnumPopup(location);
            }
            GUILayout.EndHorizontal();

            if (Selection.gameObjects.Length == 0) return;
            GUILayout.FlexibleSpace();

            if (GUILayout.Button("Apply"))
            {
                //遍历选中的所有物体
                for (int i = 0; i < Selection.gameObjects.Length; i  )
                {
                    var obj = Selection.gameObjects[i];
                    //获取模型资源所在的路径
                    string path = AssetDatabase.GetAssetPath(obj);
                    //根据路径Asset Importer并转化为Model Importer
                    ModelImporter importer = AssetImporter.GetAtPath(path) as ModelImporter;
                    //判断选中的物体是否为模型
                    if (importer != null)
                    {
                        //将materialLocation设为目标值
                        importer.materialLocation = location;
                    }
                }
            }
        }
        //选中的物体变更时调用Repaint函数重新绘制
        private void OnSelectionChange()
        {
            Repaint();
        }
    }
}

0 人点赞