Say in your Project panel you have 10 or so Materials, named aa, bb, cc …
Say in your Hierarchy you have a many objects with a MeshRenderer. Say all the objects have just one material and say many are using the Material “cc”
You want to change all the “cc” to “dd”
To be clear, in the Editor you can drag a material from the Project panel over to the Element0 slot of Materials in MeshRenderer in the Inspector. I’m just trying to do exactly that (“as if it was dragged over”) but in an editor script! Nothing more complicated than that.
At least I know how to get the selected objects that contain a renderer…see below
But I am completely cllueless on how to change the Material of one of those. More profoundly I have no idea how to get, refer to, the “dd” Material from the Assets (ie, from Project).
Help!
////////////////////// filename ChangeMaterial.cs
using UnityEngine;
using UnityEditor;
// change all selected objects using Material "cc", to "dd"
// "dd" already exists in Assets, ie you can see it in Project
public class ChangeMaterial:ScriptableObject
{
[MenuItem ("Utilities/ChangeMaterial/helloChange")]
static void __changer()
{
// something like Material newbie = asset material ("dd")
foreach (MeshRenderer mr in
Selection.GetFiltered( typeof(MeshRenderer),
SelectionMode.DeepAssets ) )
{
Debug.Log("that one was " + mr.sharedMaterial.name );
if ( mr.sharedMaterial.name == "cc" )
{
// something like mr.sharedMaterial = newbie
}
Debug.Log(" but it is now " + mr.sharedMaterial.name );
}
}
}
////////////////////////////
As you can see in my MaterialReplacer editor script here it searches the whole project folder first and identifies all materials/substances. If one of these should be used as replacement the material is loaded and the instance set. Thats the only way I figured out but it works fast and fine except for the obvious limitation if you have multiple materials/substances in your project folder with the same name.
Here is the important snippet where materials are loaded and “mapped” for replacement from the MaterialReplacer editor script.
// ------------------------------------------------------------------------
/// <summary>
/// For each transition check if the source material is used by the object and the target material exists.
/// If both is true the transition is applied in the material map.
/// </summary>
// ------------------------------------------------------------------------
private void mapApplicableTransitions( Dictionary<string,string> transitions )
{
// retrieve all materials in our project asset folder
string[] materialsInProject = Directory.GetFiles( "Assets\\", "*.mat", SearchOption.AllDirectories );
Dictionary<string, string> materialAssets = new Dictionary<string, string>();
foreach( string materialFile in materialsInProject )
materialAssets[Path.GetFileNameWithoutExtension( materialFile )] = materialFile;
// retrieve all substance archives in our project asset folder
string[] substancesInProject = Directory.GetFiles( "Assets\\", "*.sbsar", SearchOption.AllDirectories );
// cache all substance instances assets found in the dictionary since we had to load them anyway
Dictionary<string, ProceduralMaterial> substanceAssets = new Dictionary<string, ProceduralMaterial>();
foreach( string substanceFile in substancesInProject )
{
UnityEngine.Object[] objects = AssetDatabase.LoadAllAssetsAtPath( substanceFile.Replace( "\\", "/" ) );
foreach( UnityEngine.Object obj in objects )
{
ProceduralMaterial substance = obj as ProceduralMaterial;
if( substance != null )
{
try
{
substanceAssets.Add( substance.name, substance );
}
catch( ArgumentException )
{
Debug.LogError("Multiple occurences of substance '" + substance.name + "' found which will be ignored.");
}
}
}
}
// foreach object material check if a material transition with the material as source exist
StringBuilder sb = new StringBuilder().AppendLine( "Mapped Transitions:" );
foreach( Material mat in mMaterialMap.Keys )
{
string targetName;
if( transitions.TryGetValue( mat.name, out targetName ) )
{
Material targetMaterial = null;
// search for the target material
string materialAssetPath;
if( materialAssets.TryGetValue( targetName, out materialAssetPath ) )
{
targetMaterial = (Material)AssetDatabase.LoadAssetAtPath( materialAssetPath.Replace( "\\", "/" ), typeof(Material) );
}
else
{
// try to retrieve substance with the given target name
ProceduralMaterial substance;
if( substanceAssets.TryGetValue( targetName, out substance ) )
targetMaterial = substance;
}
if( targetMaterial != null )
{
mMaterialMap[mat] = targetMaterial;
sb.Append( "'" ).Append( mat.name ).Append( "' -> '" ).Append( targetMaterial.name ).AppendLine( "'" );
}
else
Debug.Log( "Material '" + targetName + "' specified in the transition file could not be found." );
}
}
Debug.Log( sb.ToString() );
}