找回密码
 立即注册
查看: 213|回复: 0

unity 导入自动强制修改资源属性

[复制链接]
发表于 2022-12-5 16:03 | 显示全部楼层 |阅读模式
网上其实有很多了,我在这里就归拢一下
模型导入设置

using UnityEditor;

public class ModelImport : AssetPostprocessor
{
    //模型导入前设置
    void OnPreprocessModel()
    {
        ModelImporter modelimporter = assetImporter as ModelImporter;

        //所有都适用
        //Model
        modelimporter.importVisibility = false;
        modelimporter.importCameras = false;
        modelimporter.importLights = false;

        modelimporter.importNormals = ModelImporterNormals.Import;

        //Materials
        modelimporter.materialImportMode = ModelImporterMaterialImportMode.ImportViaMaterialDescription;
        modelimporter.materialLocation = ModelImporterMaterialLocation.InPrefab;
        modelimporter.SearchAndRemapMaterials(ModelImporterMaterialName.BasedOnMaterialName, ModelImporterMaterialSearch.RecursiveUp);


        // 判定路径可随意修改 --->"/***/"
        //场景模型
        if (assetImporter.assetPath.Contains("Assets/Art/Builds"))
        {
            //Model
            modelimporter.importBlendShapes = false;

            //Rig
            modelimporter.animationType = ModelImporterAnimationType.None;

            //Animation
            modelimporter.importAnimation = false;
        }

        //角色模型
        if (modelimporter.assetPath.Contains("Assets/Art/Role"))
        {
            //Model
            modelimporter.importBlendShapes = true;
        }
    }
}
关于模型的导入方法里有2个
OnPostprocessModel(GameObject)    //模型导入后执行
OnPreprocessModel() //模型导入前执行
贴图导入设置

using UnityEditor;

public class TextureImport : AssetPostprocessor
{
    void OnPreprocessTexture()
    {
        TextureImporter textureimporter = (TextureImporter)assetImporter;
        if (assetImporter.assetPath.Contains("Assets/Art"))
        {
            // 判定路径可随意修改 --->"/***/"
            textureimporter.mipmapEnabled = false;
            //textureimporter.maxTextureSize = 512;
        }
        //var importer = AssetImporter.GetAtPath("Assets/Arts/TileRes") as TextureImporter;

        //{
        //    TextureImporterPlatformSettings androidSetting = new TextureImporterPlatformSettings();
        //    {
        //        androidSetting.name = "Android";
        //        androidSetting.maxTextureSize = 512;
        //        androidSetting.overridden = true;
        //    }
        //    // ios设置
        //    TextureImporterPlatformSettings iosSetting = new TextureImporterPlatformSettings();
        //    {
        //        iosSetting.name = "iPhone";
        //        iosSetting.maxTextureSize = 512;
        //        iosSetting.overridden = true;
        //    }
        //    //
        //    importer.SetPlatformTextureSettings(androidSetting);
        //    importer.SetPlatformTextureSettings(iosSetting);
        //    importer.SaveAndReimport();
        //}
    }
}
注释部分是一些修改贴图压缩的设置
关于贴图的导入方法里有4个
OnPostprocessTexture(Texture2D)    //2D贴图导入后执行
OnPostprocessTexture(Texture2DArray)    //2DArray贴图导入后执行
OnPostprocessTexture(Texture3D)    //3D贴图导入后执行
OnPreprocessTexture() //贴图导入前执行
# 材质球导入设置
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;

public class MaterialImport : AssetPostprocessor
{
    static List<string> discards = new List<string>     //如果监测到有这些shader,都会替换成上面的shader
        {
            "Standard",
            "Standard (Specular setup)",
            "Autodesk Interactive"
        };
    static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
    {
        string path = "Assets"; //需要替换的路径
        foreach (string asset in importedAssets)
        {

            if (asset.EndsWith(".mat") && asset.Contains(path))
            {
                OnPostprocessMaterial(AssetDatabase.LoadAssetAtPath<Material>(asset));
            }
        }
    }

    static void OnPostprocessMaterial(Material material)
    {
        Shader shader = Shader.Find("Custom/SimulationPBR");

        if (discards.Any(s => s.Equals(material.shader.name)))
        {
            material.shader = shader;
            MatTools.CleanMat(material);
            AssetDatabase.SaveAssets();
        }
    }
}
我遇到了一些问题,我也没有查到怎么用。
OnPostprocessMaterial()描述上说:
将此函数添加到一个子类中,以在材质资源完成导入时获取通知。
使用此方法修改导入期间新创建的材质资源的属性。
此方法仅由 ModelImporter 调用。

但是实际上我怎么测试也没有找到何时调用OnPostprocessMaterial()所以我就用了OnPostprocessAllAssets(string[],string[],string[],string[])来监测所有的导入,路径里的文件格式决定哪个是材质球来进行引用shader的修改
我在导入材质设置里还用了一个自己写的方法`MatTools.CleanMat(Material);`
这个是用来清理材质球数据的,把Standard材质里多余的数据块清理掉,减少材质球文本块数量
using UnityEditor;
using UnityEngine;

public class MatTools : Editor
{
    [MenuItem("Assets/Tools/ClearMatProperties")]
    public static void ClearMatProperties()
    {
        UnityEngine.Object[] objs = Selection.GetFiltered(typeof(Material), SelectionMode.DeepAssets);
        for (int i = 0; i < objs.Length; ++i)
        {
            Material mat = objs as Material;
            CleanMat(mat);
        }

        AssetDatabase.SaveAssets();
    }

    public static void CleanMat(Material material)
    {
        if (material)
        {
            SerializedObject psSource = new SerializedObject(material);
            SerializedProperty emissionProperty = psSource.FindProperty("m_SavedProperties");
            SerializedProperty texEnvs = emissionProperty.FindPropertyRelative("m_TexEnvs");
            SerializedProperty floats = emissionProperty.FindPropertyRelative("m_Floats");
            SerializedProperty colos = emissionProperty.FindPropertyRelative("m_Colors");

            CleanMaterialSerializedProperty(texEnvs, material);
            CleanMaterialSerializedProperty(floats, material);
            CleanMaterialSerializedProperty(colos, material);

            psSource.ApplyModifiedProperties();
            EditorUtility.SetDirty(material);
        }
    }

    /// <summary>
    /// true: has useless propeties
    /// </summary>
    /// <param name="property"></param>
    /// <param name="mat"></param>
    private static void CleanMaterialSerializedProperty(SerializedProperty property, Material mat)
    {
        for (int j = property.arraySize - 1; j >= 0; j--)
        {
            string propertyName = property.GetArrayElementAtIndex(j).displayName;
            //string propertyName = property.GetArrayElementAtIndex(j).FindPropertyRelative("first").FindPropertyRelative("name").stringValue;
            Debug.Log("Find property in serialized object : " + propertyName);
            if (!mat.HasProperty(propertyName))
            {
                if (propertyName.Equals("_MainTex"))
                {
                    //_MainTex是内建属性,是置空不删除,否则UITexture等控件在获取mat.maintexture的时候会报错
                    if (property.GetArrayElementAtIndex(j).FindPropertyRelative("second").FindPropertyRelative("m_Texture").objectReferenceValue != null)
                    {
                        property.GetArrayElementAtIndex(j).FindPropertyRelative("second").FindPropertyRelative("m_Texture").objectReferenceValue = null;
                        Debug.Log("Set _MainTex is null");
                    }
                }
                else
                {
                    property.DeleteArrayElementAtIndex(j);
                    Debug.Log("Delete property in serialized object : " + propertyName);
                }
            }
        }
    }

}
关于材质球的导入方法里有3个
//提供源材质。返回的材质将分配给渲染器。 如果返回 null,Unity 将使用其默认材质查找/生成方法来分配材质。 系统会在导入 sourceMaterial 之前直接从模型中生成 sourceMaterial,并在执行 OnAssignMaterial 之后立即将其销毁。
OnAssignMaterialModel(Material,Renderer)
//将此函数添加到一个子类中,以在材质资源完成导入时获取通知。使用此方法修改导入期间新创建的材质资源的属性。此方法仅由 ModelImporter 调用。
OnPostprocessMaterial(Material)
//将此函数添加到一个子类中,以在材质从 Model Importer 导入时接收通知。仅当 ModelImporter.UseMaterialDescriptionPostprocessor 为 true 时调用此函数。此函数提供在模型导入过程中对材质属性和动画的用户控制。MaterialDescription 结构包含在导入的文件中读取的所有材质数据,可用于填充参数中的材质和动画剪辑。
OnPreprocessMaterialDescription(MaterialDescription,Material, AnimationClip[])
但是网上我也没有搜到太多关于他们的用法,有会的大佬可以留言给我。等之后我哪天会了我也会更新。
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-5-4 05:05 , Processed in 0.145475 second(s), 25 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表