Unity中从3D模型资产中批量提取材质

如何使用
只需在“项目”窗口中创建一个名为“编辑器”的文件夹,然后在其中添加此脚本即可。然后,打开Window-Batch Extract Materials,配置参数并点击“ Extract! ”。

在Unity 2019.1+上,可以将默认材质重映射条件配置为自动检测模型资源中嵌入的重复材质并为它们提取单个材质,而不是将它们提取为重复材质实例。
在这里插入图片描述

using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.IO;

public class BatchExtractMaterials : EditorWindow
{
	private enum ExtractMode { Extract = 0, Remap = 1, Ignore = 2 };

	[System.Serializable]
	private class ExtractData
	{
		public GameObject model;

		public List<string> materialNames = new List<string>();
		public List<Material> originalMaterials = new List<Material>();
		public List<Material> remappedMaterials = new List<Material>();
		public List<ExtractMode> materialExtractModes = new List<ExtractMode>();

		public ExtractData() { }
		public ExtractData( GameObject model ) { this.model = model; }
	}

	private class RemapAllPopup : EditorWindow
	{
		private List<Material> remapFrom = new List<Material>( 2 );
		private Material remapTo;
		private bool skipIgnoredMaterials;

		private Vector2 scrollPos;

		private System.Action<List<Material>, Material, bool> onRemapConfirmed;

		public static void ShowAt( Rect buttonRect, Vector2 size, System.Action<List<Material>, Material, bool> onRemapConfirmed )
		{
			buttonRect.position = GUIUtility.GUIToScreenPoint( buttonRect.position );

			remapAllPopup = GetWindow<RemapAllPopup>( true );
			remapAllPopup.position = new Rect( buttonRect.position + new Vector2( ( buttonRect.width - size.x ) * 0.5f, buttonRect.height ), size );
			remapAllPopup.minSize = size;
			remapAllPopup.titleContent = new GUIContent( "Remap All..." );
			remapAllPopup.skipIgnoredMaterials = EditorPrefs.GetBool( "BEM_SkipIgnoredMats", true );
			remapAllPopup.onRemapConfirmed = onRemapConfirmed;
			remapAllPopup.scrollPos = Vector2.zero;
			remapAllPopup.Show();
		}

		public static void Hide()
		{
			if( remapAllPopup )
			{
				remapAllPopup.Close();
				remapAllPopup = null;
			}
		}

		private void OnDestroy()
		{
			remapAllPopup = null;
		}

		private void OnGUI()
		{
			if( !remapAllPopup )
			{
				Close();
				GUIUtility.ExitGUI();
			}

			Event ev = Event.current;

			EditorGUILayout.LabelField( "This will find all materials that point to 'Remap From' and remap them to 'Remap To'. If 'Remap From' is empty, all materials will be remapped to 'Remap To'.", EditorStyles.wordWrappedLabel );

			scrollPos = EditorGUILayout.BeginScrollView( scrollPos );

			GUILayout.BeginHorizontal();
			GUILayout.Label( "Remap From (drag & drop here)" );

			if( remapFrom.Count == 0 )
				remapFrom.Add( null );

			// Allow drag & dropping materials to array
			// Credit: https://answers.unity.com/answers/657877/view.html
			if( ( ev.type == EventType.DragPerform || ev.type == EventType.DragUpdated ) && GUILayoutUtility.GetLastRect().Contains( ev.mousePosition ) )
			{
				DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
				if( ev.type == EventType.DragPerform )
				{
					DragAndDrop.AcceptDrag();

					Object[] draggedObjects = DragAndDrop.objectReferences;
					for( int i = 0; i < draggedObjects.Length; i++ )
					{
						Material material = draggedObjects[i] as Material;
						if( !material )
							continue;

						if( !remapFrom.Contains( material ) )
						{
							bool replacedNullElement = false;
							for( int j = 0; j < remapFrom.Count; j++ )
							{
								if( !remapFrom[j] )
								{
									remapFrom[j] = material;
									replacedNullElement = true;
									break;
								}
							}

							if( !replacedNullElement )
								remapFrom.Add( material );
						}
					}
				}

				ev.Use();
			}

			if( GUILayout.Button( "+", GL_WIDTH_25 ) )
				remapFrom.Insert( 0, null );

			GUILayout.EndHorizontal();

			for( int i = 0; i < remapFrom.Count; i++ )
			{
				GUILayout.BeginHorizontal();

				remapFrom[i] = EditorGUILayout.ObjectField( GUIContent.none, remapFrom[i], typeof( Material ), false ) as Material;

				if( GUILayout.Button( "+", GL_WIDTH_25 ) )
					remapFrom.Insert( i + 1, null );

				if( GUILayout.Button( "-", GL_WIDTH_25 ) )
				{
					// Lists with no elements look ugly, always keep a dummy null variable
					if( remapFrom.Count > 1 )
						remapFrom.RemoveAt( i-- );
					else
						remapFrom[0] = null;
				}

				GUILayout.EndHorizontal();
			}

			EditorGUILayout.EndScrollView();

			remapTo = EditorGUILayout.ObjectField( "Remap To", remapTo, typeof( Material ), false ) as Material;

			EditorGUI.BeginChangeCheck();
			skipIgnoredMaterials = EditorGUILayout.Toggle( "Skip Ignored Materials", skipIgnoredMaterials );
			if( EditorGUI.EndChangeCheck() )
				EditorPrefs.SetBool( "BEM_SkipIgnoredMats", skipIgnoredMaterials );

			EditorGUILayout.Space();

			GUILayout.BeginHorizontal();
			if( GUILayout.Button( "Cancel" ) )
				Close();
			if( GUILayout.Button( "Apply" ) )
			{
				if( remapTo && onRemapConfirmed != null )
				{
					bool remapFromIsFilled = false;
					for( int i = 0; i < remapFrom.Count; i++ )
					{
						if( remapFrom[i] )
						{
							remapFromIsFilled = true;
							break;
						}
					}

					onRemapConfirmed( remapFromIsFilled ? remapFrom : null, remapTo, skipIgnoredMaterials );
				}

				Close();
			}
			GUILayout.EndHorizontal();

			GUILayout.Space( 5f );
		}
	}

	private const string HELP_TEXT =
		"- Extract: material will be extracted to the destination folder\n" +
		"- Remap: material will be remapped to an existing material asset" +
#if UNITY_2019_1_OR_NEWER
		" (when Remap is the default value, then it means that a material that satisfies 'Default Material Remap Conditions' was found)" +
#endif
		". If Remap points to an embedded material, then that embedded material will first be extracted\n" +
		"- Ignore: material's current value will stay intact (when Ignore is the default value, either the material couldn't be found " +
		"or it was already extracted)";

	private static readonly GUILayoutOption GL_WIDTH_25 = GUILayout.Width( 25f );
	private readonly GUILayoutOption GL_WIDTH_75 = GUILayout.Width( 75f );
	private readonly GUILayoutOption GL_MIN_WIDTH_50 = GUILayout.MinWidth( 50f );

	private string materialsFolder = "Assets/Materials";
	private List<ExtractData> modelData = new List<ExtractData>( 16 );

#if UNITY_2019_1_OR_NEWER
	private bool remappedMaterialNamesMustMatch = false;
	private bool remappedMaterialPropertiesMustMatch = true;
	private bool dontRemapExtractedMaterials = true;
	private bool dontRemapMaterialsAcrossDifferentModels = false;
#endif

	private bool inModelSelectionPhase = true;

	private Rect remapAllButtonRect;
	private static RemapAllPopup remapAllPopup;

	private Vector2 scrollPos;

	[MenuItem( "Window/Batch Extract Materials" )]
	private static void Init()
	{
		BatchExtractMaterials window = GetWindow<BatchExtractMaterials>();
		window.titleContent = new GUIContent( "Extract Materials" );
		window.minSize = new Vector2( 300f, 120f );
		window.Show();
	}

	private void OnDestroy()
	{
		// Close RemapAllPopup with this window
		RemapAllPopup.Hide();
	}

	private void OnFocus()
	{
		// Don't let RemapAllPopup be obstructed by this window
		// We are using delayCall because otherwise clicking an ObjectField in this window doesn't highlight that material in the Project window
		EditorApplication.delayCall += () =>
		{
			if( remapAllPopup )
				remapAllPopup.Focus();
		};
	}

	private void OnGUI()
	{
		scrollPos = EditorGUILayout.BeginScrollView( scrollPos );

		GUI.enabled = inModelSelectionPhase;
		DrawDestinationPathField();
		DrawModelsToProcessList();
		DrawMaterialRemapConditionsField();
		GUI.enabled = true;

		bool modelsToProcessListIsFilled = modelData.Find( ( data ) => data.model ) != null;

		if( inModelSelectionPhase )
		{
			GUI.enabled = modelsToProcessListIsFilled && !string.IsNullOrEmpty( materialsFolder ) && materialsFolder.StartsWith( "Assets" );
			if( GUILayout.Button( "Next" ) )
			{
				inModelSelectionPhase = false;
				CalculateRemappedMaterials();

				GUIUtility.ExitGUI();
			}
		}
		else
		{
			DrawMaterialRemapList();

			GUILayout.BeginHorizontal();

			if( GUILayout.Button( "Back" ) )
			{
				inModelSelectionPhase = true;
				RemapAllPopup.Hide();

				GUIUtility.ExitGUI();
			}

			Color c = GUI.backgroundColor;
			GUI.backgroundColor = Color.green;

			GUI.enabled = modelsToProcessListIsFilled;
			if( GUILayout.Button( "Extract!" ) )
			{
				inModelSelectionPhase = true;
				RemapAllPopup.Hide();

				ExtractMaterials();
				GUIUtility.ExitGUI();
			}

			GUI.backgroundColor = c;
			GUILayout.EndHorizontal();
		}

		GUI.enabled = true;

		EditorGUILayout.Space();
		EditorGUILayout.EndScrollView();
	}

	private void DrawDestinationPathField()
	{
		Event ev = Event.current;

		GUILayout.BeginHorizontal();

		materialsFolder = EditorGUILayout.TextField( "Extract Materials To", materialsFolder );

		// Allow drag & dropping a folder to the text field
		// Credit: https://answers.unity.com/answers/657877/view.html
		if( ( ev.type == EventType.DragPerform || ev.type == EventType.DragUpdated ) && GUILayoutUtility.GetLastRect().Contains( ev.mousePosition ) )
		{
			DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
			if( ev.type == EventType.DragPerform )
			{
				DragAndDrop.AcceptDrag();

				string[] draggedFiles = DragAndDrop.paths;
				for( int i = 0; i < draggedFiles.Length; i++ )
				{
					if( !string.IsNullOrEmpty( draggedFiles[i] ) && AssetDatabase.IsValidFolder( draggedFiles[i] ) )
					{
						materialsFolder = draggedFiles[i];
						break;
					}
				}
			}

			ev.Use();
		}

		if( GUILayout.Button( "o", GL_WIDTH_25 ) )
		{
			string selectedPath = EditorUtility.OpenFolderPanel( "Choose output directory", "Assets", "" );
			if( !string.IsNullOrEmpty( selectedPath ) )
			{
				selectedPath = selectedPath.Replace( '\\', '/' ) + "/";

				int relativePathIndex = selectedPath.IndexOf( "/Assets/" ) + 1;
				if( relativePathIndex > 0 )
					materialsFolder = selectedPath.Substring( relativePathIndex, selectedPath.Length - relativePathIndex - 1 );
			}

			GUIUtility.keyboardControl = 0; // Remove focus from active text field
		}

		GUILayout.EndHorizontal();
		EditorGUILayout.Space();
	}

	private void DrawModelsToProcessList()
	{
		Event ev = Event.current;

		GUILayout.BeginHorizontal();
		GUILayout.Label( "Models To Process (drag & drop here)" );

		if( modelData.Count == 0 )
			modelData.Add( new ExtractData() );

		// Allow drag & dropping models to array
		// Credit: https://answers.unity.com/answers/657877/view.html
		if( ( ev.type == EventType.DragPerform || ev.type == EventType.DragUpdated ) && GUILayoutUtility.GetLastRect().Contains( ev.mousePosition ) )
		{
			DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
			if( ev.type == EventType.DragPerform )
			{
				DragAndDrop.AcceptDrag();

				Object[] draggedObjects = DragAndDrop.objectReferences;
				for( int i = 0; i < draggedObjects.Length; i++ )
				{
					if( !( draggedObjects[i] as GameObject ) || PrefabUtility.GetPrefabAssetType( draggedObjects[i] ) != PrefabAssetType.Model )
						continue;

					bool modelAlreadyExists = false;
					for( int j = 0; j < modelData.Count; j++ )
					{
						if( modelData[j].model == draggedObjects[i] )
						{
							modelAlreadyExists = true;
							break;
						}
					}

					if( !modelAlreadyExists )
					{
						bool replacedNullElement = false;
						for( int j = 0; j < modelData.Count; j++ )
						{
							if( !modelData[j].model )
							{
								modelData[j] = new ExtractData( draggedObjects[i] as GameObject );
								replacedNullElement = true;
								break;
							}
						}

						if( !replacedNullElement )
							modelData.Add( new ExtractData( draggedObjects[i] as GameObject ) );
					}
				}
			}

			ev.Use();
		}

		if( GUILayout.Button( "+", GL_WIDTH_25 ) )
			modelData.Insert( 0, new ExtractData() );

		GUILayout.EndHorizontal();

		for( int i = 0; i < modelData.Count; i++ )
		{
			ExtractData element = modelData[i];

			GUI.changed = false;
			GUILayout.BeginHorizontal();

			GameObject prevObject = element.model;
			GameObject newObject = EditorGUILayout.ObjectField( GUIContent.none, prevObject, typeof( GameObject ), false ) as GameObject;
			if( newObject && PrefabUtility.GetPrefabAssetType( newObject ) != PrefabAssetType.Model )
				newObject = prevObject;

			modelData[i].model = newObject;

			if( GUILayout.Button( "+", GL_WIDTH_25 ) )
				modelData.Insert( i + 1, new ExtractData() );

			if( GUILayout.Button( "-", GL_WIDTH_25 ) )
			{
				// Lists with no elements look ugly, always keep a dummy null variable
				if( modelData.Count > 1 )
					modelData.RemoveAt( i-- );
				else
					modelData[0] = new ExtractData();
			}

			GUILayout.EndHorizontal();
		}

		EditorGUILayout.Space();
	}

	private void DrawMaterialRemapConditionsField()
	{
#if UNITY_2019_1_OR_NEWER
		EditorGUILayout.LabelField( "Default Material Remap Conditions" );
		EditorGUI.indentLevel++;

		remappedMaterialNamesMustMatch = EditorGUILayout.ToggleLeft( "Material names must match", remappedMaterialNamesMustMatch );
		remappedMaterialPropertiesMustMatch = EditorGUILayout.ToggleLeft( "Material properties must match", remappedMaterialPropertiesMustMatch );
		dontRemapExtractedMaterials = EditorGUILayout.ToggleLeft( "Don't remap already extracted materials", dontRemapExtractedMaterials );
		dontRemapMaterialsAcrossDifferentModels = EditorGUILayout.ToggleLeft( "Don't remap Model A's materials to Model B (i.e. different models won't share the same materials)", dontRemapMaterialsAcrossDifferentModels );

		EditorGUI.indentLevel--;
		EditorGUILayout.Space();
#endif
	}

	private void DrawMaterialRemapList()
	{
		EditorGUILayout.HelpBox( HELP_TEXT, MessageType.Info );

		GUILayout.BeginHorizontal();

		if( GUILayout.Button( "Extract All" ) )
		{
			for( int i = 0; i < modelData.Count; i++ )
			{
				for( int j = 0; j < modelData[i].materialExtractModes.Count; j++ )
					modelData[i].materialExtractModes[j] = ExtractMode.Extract;
			}
		}

		if( GUILayout.Button( "Remap All..." ) )
		{
			RemapAllPopup.ShowAt( remapAllButtonRect, new Vector2( 325f, 250f ), ( List<Material> remapFrom, Material remapTo, bool skipIgnoredMaterials ) =>
			{
				for( int i = 0; i < modelData.Count; i++ )
				{
					ExtractData data = modelData[i];
					for( int j = 0; j < data.remappedMaterials.Count; j++ )
					{
						switch( data.materialExtractModes[j] )
						{
							case ExtractMode.Extract:
							{
								if( remapFrom == null || ( data.originalMaterials[j] && remapFrom.Contains( data.originalMaterials[j] ) ) )
								{
									data.materialExtractModes[j] = ExtractMode.Remap;
									data.remappedMaterials[j] = remapTo;
								}

								break;
							}
							case ExtractMode.Remap:
							{
								if( remapFrom == null || ( data.remappedMaterials[j] && remapFrom.Contains( data.remappedMaterials[j] ) ) )
									data.remappedMaterials[j] = remapTo;

								break;
							}
							case ExtractMode.Ignore:
							{
								if( !skipIgnoredMaterials && ( remapFrom == null || ( data.originalMaterials[j] && remapFrom.Contains( data.originalMaterials[j] ) ) ) )
								{
									data.materialExtractModes[j] = ExtractMode.Remap;
									data.remappedMaterials[j] = remapTo;
								}

								break;
							}
						}
					}
				}

				Repaint();
			} );
		}

		if( Event.current.type == EventType.Repaint )
			remapAllButtonRect = GUILayoutUtility.GetLastRect();

		if( GUILayout.Button( "Ignore All" ) )
		{
			for( int i = 0; i < modelData.Count; i++ )
			{
				for( int j = 0; j < modelData[i].materialExtractModes.Count; j++ )
					modelData[i].materialExtractModes[j] = ExtractMode.Ignore;
			}
		}

		GUILayout.EndHorizontal();

		EditorGUILayout.Space();

		for( int i = 0; i < modelData.Count; i++ )
		{
			ExtractData data = modelData[i];
			if( !data.model )
				continue;

			GUI.enabled = false;
			EditorGUILayout.ObjectField( GUIContent.none, data.model, typeof( GameObject ), false );
			GUI.enabled = true;

			if( data.originalMaterials.Count == 0 )
				EditorGUILayout.LabelField( "This model has no materials..." );

			for( int j = 0; j < data.originalMaterials.Count; j++ )
			{
				GUILayout.BeginHorizontal();

				EditorGUILayout.PrefixLabel( data.materialNames[j] );

				data.materialExtractModes[j] = (ExtractMode) EditorGUILayout.EnumPopup( GUIContent.none, data.materialExtractModes[j], GL_WIDTH_75 );
				if( data.materialExtractModes[j] == ExtractMode.Remap )
				{
					EditorGUI.BeginChangeCheck();
					data.remappedMaterials[j] = EditorGUILayout.ObjectField( GUIContent.none, data.remappedMaterials[j], typeof( Material ), false, GL_MIN_WIDTH_50 ) as Material;
					if( EditorGUI.EndChangeCheck() && ( !data.remappedMaterials[j] || data.remappedMaterials[j] == data.originalMaterials[j] ) )
						data.materialExtractModes[j] = ExtractMode.Ignore;
				}
				else
				{
					GUI.enabled = false;
					EditorGUILayout.ObjectField( GUIContent.none, data.originalMaterials[j], typeof( Material ), false, GL_MIN_WIDTH_50 );
					GUI.enabled = true;
				}

				GUILayout.EndHorizontal();
			}

			EditorGUILayout.Space();
		}
	}

	private void CalculateRemappedMaterials()
	{
#if UNITY_2019_1_OR_NEWER
		// Key: Material CRC (material.ComputeCRC)
		// Value: All materials sharing that CRC
		Dictionary<int, HashSet<Material>> duplicateMaterialsLookup = new Dictionary<int, HashSet<Material>>( modelData.Count * 8 );

		// Add all existing materials at materialsFolder to the lookup table
		if( !dontRemapMaterialsAcrossDifferentModels && Directory.Exists( materialsFolder ) )
		{
			string[] existingMaterialPaths = Directory.GetFiles( materialsFolder, "*.mat", SearchOption.TopDirectoryOnly );
			for( int i = 0; i < existingMaterialPaths.Length; i++ )
			{
				Material material = AssetDatabase.LoadMainAssetAtPath( existingMaterialPaths[i] ) as Material;
				if( material )
					GetMaterialsWithCRC( duplicateMaterialsLookup, material ).Add( material );
			}
		}
#endif

		for( int i = 0; i < modelData.Count; i++ )
		{
			ExtractData data = modelData[i];
			if( !data.model )
			{
				modelData.RemoveAt( i-- );
				continue;
			}

			string modelPath = AssetDatabase.GetAssetPath( data.model );
			ModelImporter modelImporter = AssetImporter.GetAtPath( modelPath ) as ModelImporter;
			if( !modelImporter )
			{
				Debug.LogWarning( "Couldn't get ModelImporter from asset: " + AssetDatabase.GetAssetPath( data.model ), data.model );
				modelData.RemoveAt( i-- );
				continue;
			}

			// Reset previously assigned values to this entry (if any)
			data = modelData[i] = new ExtractData( data.model );

			Object[] embeddedAssets = AssetDatabase.LoadAllAssetRepresentationsAtPath( modelPath );
			List<Material> embeddedMaterials = new List<Material>( embeddedAssets.Length );
			for( int j = 0; j < embeddedAssets.Length; j++ )
			{
				Material embeddedMaterial = embeddedAssets[j] as Material;
				if( embeddedMaterial )
					embeddedMaterials.Add( embeddedMaterial );
			}

			// Get the model's current material remapping
			// Credit: https://forum.unity.com/threads/batch-change-all-fbx-default-materials-help.626341/#post-6530939
			using( SerializedObject so = new SerializedObject( modelImporter ) )
			{
				SerializedProperty materials = so.FindProperty( "m_Materials" );
				SerializedProperty externalObjects = so.FindProperty( "m_ExternalObjects" );

				for( int materialIndex = 0; materialIndex < materials.arraySize; materialIndex++ )
				{
					SerializedProperty id = materials.GetArrayElementAtIndex( materialIndex );
					string name = id.FindPropertyRelative( "name" ).stringValue;
					string type = id.FindPropertyRelative( "type" ).stringValue;

					Material material = null;
					for( int externalObjectIndex = 0; externalObjectIndex < externalObjects.arraySize; externalObjectIndex++ )
					{
						SerializedProperty pair = externalObjects.GetArrayElementAtIndex( externalObjectIndex );
						string externalName = pair.FindPropertyRelative( "first.name" ).stringValue;
						string externalType = pair.FindPropertyRelative( "first.type" ).stringValue;

						if( externalType == type && externalName == name && ( pair = pair.FindPropertyRelative( "second" ) ) != null )
						{
							material = pair.objectReferenceValue as Material;
							break;
						}
					}

					if( !material )
						material = embeddedMaterials.Find( ( m ) => m.name == name );

					data.materialNames.Add( name );
					data.originalMaterials.Add( material );

					if( !material )
					{
						data.materialExtractModes.Add( ExtractMode.Ignore );
						data.remappedMaterials.Add( null );
					}
					else
					{
						bool materialAlreadyExtracted = AssetDatabase.IsMainAsset( material );
#if UNITY_2019_1_OR_NEWER
						HashSet<Material> duplicateMaterials = GetMaterialsWithCRC( duplicateMaterialsLookup, material );
						Material remappedMaterial = null;

						// - Material was already extracted: remap the material only if 'dontRemapExtractedMaterials' is false
						// - 'dontRemapMaterialsAcrossDifferentModels' is true: only remap with a material from the same model
						// - 'remappedMaterialPropertiesMustMatch' is true: only remap with a material whose properties match
						//   the current material's properties
						// - Only 'remappedMaterialNamesMustMatch' is true: remap with a material with the same name; properties
						//   of the two materials may not match
						if( !materialAlreadyExtracted || !dontRemapExtractedMaterials )
						{
							if( remappedMaterialPropertiesMustMatch )
							{
								foreach( Material _material in duplicateMaterials )
								{
									if( _material.name == name || ( !remappedMaterial && !remappedMaterialNamesMustMatch ) )
										remappedMaterial = _material;
								}
							}
							else if( remappedMaterialNamesMustMatch )
								remappedMaterial = GetMaterialWithName( duplicateMaterialsLookup, name );
						}

						if( remappedMaterial && remappedMaterial != material )
						{
							data.materialExtractModes.Add( ExtractMode.Remap );
							data.remappedMaterials.Add( remappedMaterial );
						}
						else
#endif
						{
							data.materialExtractModes.Add( materialAlreadyExtracted ? ExtractMode.Ignore : ExtractMode.Extract );
							data.remappedMaterials.Add( null );

#if UNITY_2019_1_OR_NEWER
							duplicateMaterials.Add( material );
#endif
						}
					}
				}
			}

#if UNITY_2019_1_OR_NEWER
			if( dontRemapMaterialsAcrossDifferentModels )
				duplicateMaterialsLookup.Clear();
#endif
		}
	}

#if UNITY_2019_1_OR_NEWER
	private HashSet<Material> GetMaterialsWithCRC( Dictionary<int, HashSet<Material>> lookup, Material material )
	{
		int crcHash = material.ComputeCRC();
		HashSet<Material> result;
		if( !lookup.TryGetValue( crcHash, out result ) )
			lookup[crcHash] = result = new HashSet<Material>();

		return result;
	}

	private Material GetMaterialWithName( Dictionary<int, HashSet<Material>> lookup, string name )
	{
		foreach( HashSet<Material> allMaterials in lookup.Values )
		{
			foreach( Material material in allMaterials )
			{
				if( material.name == name )
					return material;
			}
		}

		return null;
	}
#endif

	private void ExtractMaterials()
	{
		if( materialsFolder.EndsWith( "/" ) )
			materialsFolder = materialsFolder.Substring( 0, materialsFolder.Length - 1 );

		if( !Directory.Exists( materialsFolder ) )
		{
			Directory.CreateDirectory( materialsFolder );
			AssetDatabase.ImportAsset( materialsFolder, ImportAssetOptions.ForceUpdate );
		}

		List<AssetImporter> dirtyModelImporters = new List<AssetImporter>( modelData.Count );
		Dictionary<Material, Material> extractedMaterials = new Dictionary<Material, Material>( modelData.Count * 8 );

		for( int i = 0; i < modelData.Count; i++ )
		{
			ExtractData data = modelData[i];
			if( !data.model )
				continue;

			AssetImporter modelImporter = AssetImporter.GetAtPath( AssetDatabase.GetAssetPath( data.model ) );

			// Remap/extract the model's materials
			// Credit: https://forum.unity.com/threads/batch-change-all-fbx-default-materials-help.626341/#post-6530939
			using( SerializedObject so = new SerializedObject( modelImporter ) )
			{
				SerializedProperty materials = so.FindProperty( "m_Materials" );
				SerializedProperty externalObjects = so.FindProperty( "m_ExternalObjects" );

				for( int materialIndex = 0; materialIndex < materials.arraySize; materialIndex++ )
				{
					SerializedProperty id = materials.GetArrayElementAtIndex( materialIndex );
					string name = id.FindPropertyRelative( "name" ).stringValue;
					string type = id.FindPropertyRelative( "type" ).stringValue;

					// j: index of the target material in data's lists
					int j = ( materialIndex < data.materialNames.Count && data.materialNames[materialIndex] == name ) ? materialIndex : data.materialNames.IndexOf( name );
					if( j < 0 )
					{
						// This can only occur if user reimports the model with more materials when 'inModelSelectionPhase' is false
						Debug.LogWarning( data.model.name + "." + name + " material has no matching data, skipped", data.model );
						continue;
					}

					Material targetMaterial = null;
					switch( data.materialExtractModes[j] )
					{
						case ExtractMode.Extract:
						{
							if( data.originalMaterials[j] && !AssetDatabase.IsMainAsset( data.originalMaterials[j] ) )
								targetMaterial = data.originalMaterials[j];
							else
								Debug.LogWarning( data.model.name + "." + name + " isn't extracted because either the material doesn't exist or it is already extracted", data.model );

							break;
						}
						case ExtractMode.Remap:
						{
							if( data.remappedMaterials[j] && ( data.originalMaterials[j] != data.remappedMaterials[j] || !AssetDatabase.IsMainAsset( data.remappedMaterials[j] ) ) )
								targetMaterial = data.remappedMaterials[j];
							else
								Debug.LogWarning( data.model.name + "." + name + " isn't remapped because either the material doesn't exist or it is already extracted", data.model );

							break;
						}
					}

					if( !targetMaterial )
						continue;
					else if( !AssetDatabase.IsMainAsset( targetMaterial ) )
					{
						Material extractedMaterial;
						if( !extractedMaterials.TryGetValue( targetMaterial, out extractedMaterial ) )
						{
							extractedMaterials[targetMaterial] = extractedMaterial = new Material( targetMaterial );
							AssetDatabase.CreateAsset( extractedMaterial, AssetDatabase.GenerateUniqueAssetPath( materialsFolder + "/" + targetMaterial.name + ".mat" ) );
						}

						targetMaterial = extractedMaterial;
					}

					SerializedProperty materialProperty = null;
					for( int externalObjectIndex = 0; externalObjectIndex < externalObjects.arraySize; externalObjectIndex++ )
					{
						SerializedProperty pair = externalObjects.GetArrayElementAtIndex( externalObjectIndex );
						string externalName = pair.FindPropertyRelative( "first.name" ).stringValue;
						string externalType = pair.FindPropertyRelative( "first.type" ).stringValue;

						if( externalType == type && externalName == name )
						{
							materialProperty = pair.FindPropertyRelative( "second" );
							break;
						}
					}

					if( materialProperty == null )
					{
						SerializedProperty currentSerializedProperty = externalObjects.GetArrayElementAtIndex( externalObjects.arraySize++ );
						currentSerializedProperty.FindPropertyRelative( "first.name" ).stringValue = name;
						currentSerializedProperty.FindPropertyRelative( "first.type" ).stringValue = type;
						currentSerializedProperty.FindPropertyRelative( "first.assembly" ).stringValue = id.FindPropertyRelative( "assembly" ).stringValue;
						currentSerializedProperty.FindPropertyRelative( "second" ).objectReferenceValue = targetMaterial;
					}
					else
						materialProperty.objectReferenceValue = targetMaterial;
				}

				if( so.hasModifiedProperties )
				{
					dirtyModelImporters.Add( modelImporter );
					so.ApplyModifiedPropertiesWithoutUndo();
				}
			}
		}

		for( int i = 0; i < dirtyModelImporters.Count; i++ )
			dirtyModelImporters[i].SaveAndReimport();
	}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/107738.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

RSA:基于小加密指数的攻击方式与思维技巧

目录 目录 目录 零、前言 一、小加密指数爆破 [FSCTF]RSA签到 思路&#xff1a; 二、基于小加密指数的有限域开根 [NCTF 2019]easyRSA 思路&#xff1a; 三、基于小加密指数的CRT [0CTF 2016] rsa 思路&#xff1a; 零、前言 最近&#xff0c;发现自己做题思路比较…

SpringCore完整学习教程5,入门级别

本章从第6章开始 6. JSON Spring Boot提供了三个JSON映射库的集成: Gson Jackson JSON-B Jackson是首选的和默认的库。 6.1. Jackson 为Jackson提供了自动配置&#xff0c;Jackson是spring-boot-starter-json的一部分。当Jackson在类路径上时&#xff0c;将自动配置Obj…

Java 将数据导出到Excel并发送到在线文档

一、需求 现将列表数据&#xff0c;导出到excel,并将文件发送到在线文档&#xff0c;摒弃了以往的直接在前端下载的老旧模式。 二、pom依赖 <!-- redission --><dependency><groupId>org.redisson</groupId><artifactId>redisson-spring-boot-…

UE5 C++自定义Http节点获得Header数据

一、新建C文件 选择All Classes&#xff0c;选择父类BlueprintFunctionLibrary&#xff0c;命名为SendHttpRequest。 添加Http支持 代理回调的参数使用DECLARE_DYNAMIC_DELEGATE_TwoParam定义&#xff0c;第一参数是代理类型&#xff0c;后面是参数1类型&#xff0c;参数1&…

APP自动化测试 ---- Appium介绍及运行原理

在面试APP自动化时&#xff0c;有的面试官可能会问Appium的运行原理&#xff0c;以下介绍Appium运行原理。 一、Appium介绍 1.Appium概念 Appium是一个开源测试自动化框架&#xff0c;可用于原生&#xff0c;混合和移动Web应用程序测试。它使用WebDriver协议驱动IOS&#xf…

33:深入浅出x86中断机制

背景 我们知道使用0x10号中断&#xff0c;可以在屏幕上打印一个字符。 问题 系统中的 中断 究竟是什么&#xff1f; 生活中的例子 来看一个生活中例子&#xff1a; 小狄的工作方式 在处理紧急事务的时候&#xff0c;不回应同事的技术求助。老板的召唤必须回应&#xff0c;…

C/C++面试常见问题——const关键字的作用和用法

首先我们需要一下const关键字的定义&#xff0c;const名叫常量限定符&#xff0c;当const修饰变量时&#xff0c;就是在告诉编译器该变量只可访问不可修改&#xff0c;而编译器对于被const修饰的变量有一个优化&#xff0c;编译器不会专门为其开辟空间&#xff0c;而是将变量名…

linux入门---多线程的控制

目录标题 线程库pthread_create如何一次性创建多个线程线程的终止线程的等待线程取消分离线程如何看待其他语言支持的多线程线程id的本质线程的局部存储线程的封装 线程库 要想控制线程就得使用原生线程库也可以将其称为pthread库&#xff0c;这个库是遵守posix标准的&#xf…

【AD9361 数字接口CMOS LVDSSPI】B 并行数据之CMOS 续

续【AD9361 数字接口CMOS &LVDS&SPI】B 并行数据之CMOS 数据总线空闲和周转周期 &#xff08;CMOS&#xff09; P0_D[11&#xff1a;0]和P1_D[11&#xff1a;0]总线信号通常由BBP或AD9361有源驱动。在任何空闲期间&#xff0c;两个组件都会忽略数据总线值。但是&…

【Linux】权限完结

个人主页点击直达&#xff1a;小白不是程序媛 系列专栏&#xff1a;Linux被操作记 目录 前言 chown指令 chgrp指令 文件类型 file指令 目录的权限 粘滞位 umask指令 权限总结 前言 上篇文章我们说到对于一个文件所属者和所属组都是同一个人时&#xff0c;使用所属者身…

计算机操作系统重点概念整理-第五章 文件管理【期末复习|考研复习】

第五章 文件管理 【期末复习|考研复习】 计算机操作系统系列文章传送门&#xff1a; 第一章 计算机系统概述 第二章 进程管理 第三章 进程同步 第四章 内存管理 第五章 文件管理 第六章 输出输出I/O管理 文章目录 第五章 文件管理 【期末复习|考研复习】前言五、文件管理5.1 文…

使用pycharm远程调试

使用pycharm 专业版&#xff0c; 在设置解释器中&#xff0c;具备ssh 解释器功能&#xff1b; 一般在本地无法调试远程端代码&#xff0c;机械性的scp传输文件十分影响工作效率&#xff0c;PyCharm的Pro支持远程Run&#xff0c;Debug&#xff0c;等可视化的功能。 操作系统&…

自动驾驶之—2D到3D升维

前言&#xff1a; 最近在学习自动驾驶方向的东西&#xff0c;简单整理一些学习笔记&#xff0c;学习过程中发现宝藏up 手写AI 3D卷积 3D卷积的作用&#xff1a;对于2DCNN&#xff0c;我们知道可以很好的处理单张图片中的信息&#xff0c;但是其对于视频这种由多帧图像组成的图…

FPGA_状态机工作原理

FPGA_状态机介绍和工作原理 状态机工作原理Mealy 状态机模型Moore 状态机模型状态机描述方式代码格式 总结 状态机工作原理 状态机全称是有限状态机&#xff08;Finite State Machine、FSM&#xff09;&#xff0c;是表示有限个状态以及在这些状态之间的转移和动作等行为的数学…

Istio 运行错误 failed to update resource with server-side apply for obj 问题解决

Istio 环境 kubernetes version: v1.18.2 istio version: v1.10.0运行之后 istio-operator 的日志就抛出下面错误&#xff0c;而且会一直重启 # kubectl get iop -A NAMESPACE NAME REVISION STATUS AGE istio-system iop-pro-cluster…

JVM进阶(1)

一)JVM是如何运行的&#xff1f; 1)在程序运行前先将JAVA代码转化成字节码文件也就是class文件&#xff0c;JVM需要通过类加载器将字节码以一定的方式加载到JVM的内存运行时数据区&#xff0c;将类的信息打包分块填充在运行时数据区&#xff1b; 2)但是字节码文件是JVM的一套指…

高三高考免费试卷真题押题知识点合集

发表于安徽 温馨提示&#xff1a;有需要的真题试卷可联系本人&#xff0c;百卷内上免费资源。 感觉有用的下方三连&#xff0c;谢谢 ​ 。 免费版卷有6-60卷每卷平均4-30页 高三免费高三地理高三英语高三化学高三物理高三语文高三历史高三政治高三数学高三生物 付费版卷有1…

适用于 Mac 或 Windows 的 4 种最佳 JPEG/PNG图片 恢复软件

您的计算机或外部存储驱动器上很可能有大量 JPEG /PNG图片照片&#xff0c;但不知何故&#xff0c;您意识到一些重要的 JPEG /PNG图片文件丢失或被删除&#xff0c;它们对您来说意义重大&#xff0c;您想要找回它们. 4 种最佳 JPEG/PNG图片 恢复软件 要成功执行 JPEG /PNG图片…

面试题复盘-2023/10/20

目录 笔试题面试题&#xff08;未完待续&#xff09; 笔试题 一.多选题 A:map的key是const,不可更改 B:STL中的快速排序比一般的快速排序速度更快&#xff0c;是因为中值排序法 C:list的插入效率是O(1) D:vector的容量只能增大不能减小 解析&#xff1a; B: STL中的sort函数的…

父子项目打包发布至私仓库

父子项目打包发布至私仓库 1、方法一 在不需要发布至私仓的模块上添加如下代码&#xff1a; <plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-deploy-plugin</artifactId><configuration><skip>true</s…