ChangeMaterialOnSelection

From Unify Community Wiki
Jump to: navigation, search

Author: Casemon (Casemon)

Description

This Wizard lets you set the material on the current selection. Also has toggles for include / excluding prefabs or children. Helps you change materials 'en masse' as needed, especially useful when using prefabs and need to change material on only a subset of them.

Usage

You must place the script in a folder named Editor in your projects Assets folder for it to work properly.

Select the objects you want to change the material on and launch the Wizard by clicking on Custom => Set Selection to Material. It will let you specify you which material to change to and whether to include children (on selected objects) or exclude prefabs (if selection includes instances).

Will fail if you have an element in the selection that does not have a Mesh Renderer component.

C# - SetSelectionToMaterial.cs

using UnityEngine;
using UnityEditor;
 
public class SetSelectionToMaterial : ScriptableWizard
{
    public Material material;
    public bool includeChildren;
    public bool excludePrefabs;
    private SelectionMode modePrefs; 
 
    [MenuItem ("Custom/Set Selection to Material %e")]
    static void DoSet()
    {
        ScriptableWizard.DisplayWizard("Set Selection to Material", typeof(SetSelectionToMaterial), "Set");
 
    }
 
    void OnWizardUpdate()
    {
        helpString = "Set the material of the objects in the selection to this. Tick Include Children to also set material on the children of selected objects or tick Exclude Prefabs if you don't want instanced objects (from prefabs) to be changed.";
    }
 
 
    void OnWizardCreate()
    {
 
        if(includeChildren || excludePrefabs)
 
        modePrefs=(SelectionMode.ExcludePrefab | SelectionMode.Editable | SelectionMode.Deep);
        else
            modePrefs=(SelectionMode.Editable);
 
        Object[] objs = Selection.GetFiltered(typeof(GameObject), modePrefs);
 
        foreach (GameObject go in objs)
        {
            go.renderer.material = material;
        }
 
/* if you replace the above foreach with my version below, it seems to work well for cases where some children parts don't have a renderer:
 
        foreach (GameObject go in objs)
        {
            if (go.renderer)
            	go.renderer.material = material;
        }
 
*/
 
    }   
}
Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Tools