- Home /
Extract Materials from fbx via script
hey guys,
I'm working on a modelimporter right now, and it works quite well. I just encountered the problem now, that I can't seem to find a option to extract materials from script.
There is the 'Extract Materials ...' Button, but even in the https://docs.unity3d.com/ScriptReference/ModelImporter.html documentation there is no point about the Extraction of materials, but there is for textures
Anyone in here got an idea on how to do it from script?
Answer by Exa-Adoran · Oct 16, 2019 at 12:22 PM
Hey guys,
I had the same issue and just looked up the UnityEditor.dll what they are exactly doing. I found out that the method "ExtractMaterialsFromAsset" is part of the PrefabUtlity, but not public accessible. I just copied and customized their code and it works fine fore me.
This method is part of my custom AssetImporter Script, but i guess you can put it in any EditorScript
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
public static void ExtractMaterials(string assetPath, string destinationPath)
{
HashSet<string> hashSet = new HashSet<string>();
IEnumerable<Object> enumerable = from x in AssetDatabase.LoadAllAssetsAtPath(assetPath)
where x.GetType() == typeof(Material)
select x;
foreach (Object item in enumerable)
{
string path = System.IO.Path.Combine(destinationPath, item.name) + ".mat";
path = AssetDatabase.GenerateUniqueAssetPath(path);
string value = AssetDatabase.ExtractAsset(item, path);
if (string.IsNullOrEmpty(value))
{
hashSet.Add(assetPath);
}
}
foreach (string item2 in hashSet)
{
AssetDatabase.WriteImportSettingsIfDirty(item2);
AssetDatabase.ImportAsset(item2, ImportAssetOptions.ForceUpdate);
}
}
Here is how you can call the Function:
CustomModelImporter.ExtractMaterials("Assets/MyGame.fbx", "Assets");
Kind regards
Do you have further example? They could be screenshots reveling the way to use it. Generic elements like Hashset and IEnumeration are kinda new to me (and anyone else)
Thanks
Answer by real2u · Jul 12, 2019 at 11:51 AM
Bump! Same issue here, couldn´t fidn a way to reach it via script also