Hammeee
Hammeee

Reputation: 85

How to get the material name that imported from fbx via script in unity?

enter image description here This is my import setting for a FBX file, what I want to get is the material name that imported from 3dsmax, but I can't find a way to achieve it properly. What I have tried is OnPreprocessMaterialDescription() (https://docs.unity3d.com/ScriptReference/AssetPostprocessor.OnPreprocessMaterialDescription.html), from my understanding, the material description include the name info I want, and my code is blow, the OnPreprocessMaterialDescription() seems not working, it print out nothing. Or is there any other way to get the name info i need? please help, thanks in advance!

public class Test : AssetPostprocessor
{
    private void OnPreprocessModel()
    {
        var modelImporter = assetImporter as ModelImporter;
        //set material imported mode to material description
        modelImporter.materialImportMode = ModelImporterMaterialImportMode.ImportViaMaterialDescription;
    }
    public void OnPreprocessMaterialDescription(MaterialDescription description, Material material, AnimationClip[] materialAnimation)
    {
        Debug.Log(description.materialName);
    }

}

Upvotes: 1

Views: 1505

Answers (2)

h00w
h00w

Reputation: 825

You can use SerializedObject to get any editor data not exposed by the Unity API.

class Test1
{
        [MenuItem("Assets/Print Material Names In Selected Model Importer", false)]
        private static void Print()
        {
            var asset = Selection.activeObject;
            var importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(asset));

            var so = new SerializedObject(importer);
            var materials = so.FindProperty("m_Materials");
            for (int i = 0, e = materials.arraySize; i < e; ++i)
            {
                Debug.Log(materials.GetArrayElementAtIndex(i).FindPropertyRelative("name").stringValue);
            }
        }
}

Upvotes: 1

I don't know why your code in particular does not work, but if you don't insist on preprocessing, the model is already structured in the Unity-typical way on post-process so you can just access the materials like you would in a scene object:

void OnPostprocessModel(GameObject model) {
   
 foreach(MeshRenderer mr in model.GetComponentsInChildren<MeshRenderer>()) {
   
  Debug.Log(mr.sharedMaterial);
 }
}

Upvotes: 1

Related Questions