Created
December 27, 2025 03:00
-
-
Save nomnomab/936c9e374a81083ce4c954d0c369e496 to your computer and use it in GitHub Desktop.
Context menu item to bulk extract model file materials to a folder.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #if UNITY_EDITOR | |
| using System.Collections.Generic; | |
| using System.IO; | |
| using System.Linq; | |
| using UnityEditor; | |
| using UnityEngine; | |
| static class ExtractModelMaterials { | |
| static readonly string[] ModelExtensions = { | |
| ".fbx", | |
| ".obj", | |
| ".blend" | |
| }; | |
| [MenuItem("Assets/Extract Materials")] | |
| static void Extract() { | |
| var outputPath = EditorUtility.OpenFolderPanel("Select Materials Folder", Application.dataPath, string.Empty); | |
| if (string.IsNullOrEmpty(outputPath)) return; | |
| if (!outputPath.StartsWith(Application.dataPath)) { | |
| return; | |
| } | |
| outputPath = "Assets/" + outputPath[Application.dataPath.Length..]; | |
| AssetDatabase.StartAssetEditing(); | |
| foreach (var guid in Selection.assetGUIDs) { | |
| var assetPath = AssetDatabase.GUIDToAssetPath(guid); | |
| if (string.IsNullOrEmpty(assetPath)) continue; | |
| ExtractMaterials(assetPath, outputPath); | |
| } | |
| AssetDatabase.StopAssetEditing(); | |
| } | |
| [MenuItem("Assets/Extract Materials", validate = true)] | |
| static bool ValidateExtract() { | |
| if (Selection.count == 0) return false; | |
| return Selection.assetGUIDs.All(IsModel); | |
| } | |
| static bool IsModel(string guid) { | |
| var path = AssetDatabase.GUIDToAssetPath(guid); | |
| if (string.IsNullOrEmpty(path)) return false; | |
| var extension = Path.GetExtension(path); | |
| if (ModelExtensions.Contains(extension)) { | |
| return true; | |
| } | |
| return false; | |
| } | |
| public static void ExtractMaterials(string assetPath, string destinationPath) { | |
| var hashSet = new HashSet<string>(64); | |
| var enumerable = AssetDatabase | |
| .LoadAllAssetsAtPath(assetPath) | |
| .Where(x => x is Material); | |
| foreach (var item in enumerable) { | |
| var path = System.IO.Path.Combine(destinationPath, item.name) + ".mat"; | |
| path = AssetDatabase.GenerateUniqueAssetPath(path); | |
| var 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); | |
| } | |
| } | |
| } | |
| #endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment