Skip to content

Instantly share code, notes, and snippets.

@TocaLucas
Last active September 8, 2019 15:45
Show Gist options
  • Save TocaLucas/6579712 to your computer and use it in GitHub Desktop.
Save TocaLucas/6579712 to your computer and use it in GitHub Desktop.
Unity3D Material Replace Editor
using UnityEngine;
using UnityEditor;
public class ReplaceMaterials : EditorWindow {
static int goCount = 0, replaceCount = 0;
private Material currentMaterial = null;
private Material replaceMaterial = null;
[MenuItem("Stuff/Replace Materials")]
public static void ShowWindow() {
EditorWindow.GetWindow(typeof(ReplaceMaterials));
}
public void OnGUI() {
currentMaterial = EditorGUILayout.ObjectField("Material", currentMaterial, typeof(Material), false) as Material;
string matName = (currentMaterial != null) ? currentMaterial.name : "null";
if(GUILayout.Button("Replace All Materials with "+matName+" (Recursive)")) {
replaceMaterial = null;
ReplaceSelected(currentMaterial, replaceMaterial, true);
}
if(GUILayout.Button("Replace Materials with"+matName)) {
replaceMaterial = null;
ReplaceSelected(currentMaterial, replaceMaterial, false);
}
replaceMaterial = EditorGUILayout.ObjectField("Replace Material", replaceMaterial, typeof(Material), false) as Material;
string reMatName = (replaceMaterial != null) ? replaceMaterial.name : "null";
if(GUILayout.Button("Replace All "+reMatName+" with "+matName+" (Recursive)")) {
ReplaceSelected(currentMaterial, replaceMaterial, true);
}
if(GUILayout.Button("Replace "+reMatName+" with "+matName)) {
ReplaceSelected(currentMaterial, replaceMaterial, false);
}
}
private static void ReplaceSelected(Material material, Material replaceMaterial, bool recursive) {
GameObject[] go = Selection.gameObjects;
goCount = 0;
replaceCount = 0;
foreach(GameObject g in go) {
ReplaceInGO(g, material, replaceMaterial, recursive);
}
Debug.Log(string.Format("Searched {0} GameObjects, replaced {2} materials", goCount, replaceCount));
}
private static void ReplaceInGO(GameObject g, Material material, Material replaceMaterial, bool recursive) {
goCount++;
MeshRenderer[] mrs = g.GetComponentsInChildren<MeshRenderer>();
foreach(MeshRenderer mr in mrs) {
if(replaceMaterial == null || mr.sharedMaterial == replaceMaterial) {
replaceCount++;
mr.sharedMaterial = material;
}
}
SkinnedMeshRenderer[] smrs = g.GetComponentsInChildren<SkinnedMeshRenderer>();
foreach(SkinnedMeshRenderer smr in smrs) {
if(replaceMaterial == null || smr.sharedMaterial == replaceMaterial) {
replaceCount++;
smr.sharedMaterial = material;
}
}
if(recursive)
foreach(Transform childT in g.transform)
ReplaceInGO(childT.gameObject, material, replaceMaterial, recursive);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment