Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by Fattie · Nov 01, 2012 at 02:13 PM · editoreditor-scriptingmaterials

Editor script .. change a material

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! :O

 ////////////////////// 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 );
       }
    }
 }
 ////////////////////////////
Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Seth-Bergman · Nov 01, 2012 at 03:45 PM 0
Share

I think you need to use the Resources folder to find the materials dynamically..

http://docs.unity3d.com/Documentation/ScriptReference/Resources.html

to set the material, I would just use:

mr.material = newbie;

I think shared$$anonymous$$aterial is used for changing parameters of a specific material, but across all instances..

I usually just say:

gameObject.renderer.material = new$$anonymous$$aterial;

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by xadhoom · Nov 05, 2012 at 01:33 AM

Hi,

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() );
     }

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Fattie · Nov 05, 2012 at 06:49 AM 0
Share

thanks for that great tip. it's interesting that you "have to load it" to get at it.

Thanks again, really !!!!

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

12 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How can i create a pup-up menu like the one for choose the shader on materials in unity 2019? 1 Answer

How to access empty Material slots on a ModelImporter via script? 1 Answer

Start/Stop Playmode from editor script 10 Answers

Draw specific Object Inspector into Rect 1 Answer

Editor Window Views 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges