Search Unity

Trouble with an editor script replacing materials

Discussion in 'Scripting' started by Bluestrike, Jun 26, 2013.

  1. Bluestrike

    Bluestrike

    Joined:
    Sep 26, 2009
    Posts:
    256
    Hmm something seems wrong with unity awsers (missing post button under ask a question)
    So lets try here.

    In the code below I search for a material with a specific name in my selection and replace it with supplied material.
    My debug log reports a changed material name but in my view nothing happens and the object still has the same material.

    Any clue whats wrong with my script?

    Code (csharp):
    1. public class SwitchMaterialsTest extends ScriptableWizard
    2. {
    3.     var replaceMaterialName     :String;
    4.     var newMaterial             :Material;
    5.  
    6.  
    7.     new function OnGUI() :void
    8.     {
    9.         var allowSceneObjects : boolean = !EditorUtility.IsPersistent (this);
    10.        
    11.         replaceMaterialName = EditorGUILayout.TextField("replace material name: ", replaceMaterialName);
    12.         newMaterial = EditorGUILayout.ObjectField("new material:", newMaterial, Material, allowSceneObjects);
    13.  
    14.         if(GUILayout.Button("Replace"))
    15.         {
    16.             Replace();
    17.         }
    18.     }
    19.  
    20.     @MenuItem("test/Switch Materials test")
    21.     static function Init() :void
    22.     {
    23.         var window :SwitchMaterialsTest = EditorWindow.GetWindow(SwitchMaterialsTest, false, "Material Switcher");
    24.     }
    25.    
    26.    
    27.    
    28.     function Replace() :void
    29.     {
    30.         for (var item :GameObject  in Selection.gameObjects)
    31.         {
    32.             // Grab all renderers in gameobjects and childs
    33.             var rRenderers = item.GetComponentsInChildren(Renderer);
    34.            
    35.             for (var rRenderer :Renderer in rRenderers)
    36.             {
    37.                 var materials = rRenderer.sharedMaterials;
    38.  
    39.                 for(var mat :Material in materials)
    40.                 {
    41.                     if(mat.name == replaceMaterialName)
    42.                     {
    43.                         mat = newMaterial;
    44.                         Debug.Log(mat.name);
    45.                     }
    46.                  }
    47.              }
    48.          } 
    49.     }
    50. }