using UnityEngine;
using System.Collections;
using UnityEditor;
public class ApplyMaterial : EditorWindow
{
public static string [] config =
{
".PNG",".JPG",".TGA"
};
[MenuItem ("Window/ApplyMaterial")]
static void Applay ()
{
Rect wr = new Rect (0,0,500,500);
ApplyMaterial window = (ApplyMaterial)EditorWindow.GetWindowWithRect (typeof (ApplyMaterial),wr,true,"关联材质");
window.Show();
}
void OnGUI()
{
if (GUILayout.Button("批量关联材质"))
{
ApplayMatrials(true);
}
if (GUILayout.Button("批量删除关联"))
{
ApplayMatrials(false);
}
}
void ApplayMatrials(bool isAdd)
{
if (Selection.activeGameObject != null)
{
foreach (GameObject g in Selection.gameObjects)
{
Renderer[] renders = g.GetComponentsInChildren<Renderer>();
foreach (Renderer r in renders)
{
if (r != null)
{
foreach (Object o in r.sharedMaterials)
{
string path = AssetDatabase.GetAssetPath(o);
Material m = AssetDatabase.LoadAssetAtPath(path, typeof(Material)) as Material;
if (isAdd)
{
if (m.mainTexture == null)
{
Texture t = GetTexture(m.name);
if (t != null)
{
m.mainTexture = t;
}
else
{
Debug.Log("材质名:" + o.name + " 材质替换失败,请检查资源");
}
Texture t_n = GetTexture(m.name + "_n");
if(t_n!=null)
{
m.SetTexture("_BumpMap", t_n);
}
else
{
Debug.Log("材质名:" + o.name + " 材质替换失败,请检查资源");
}
Texture t_m = GetTexture(m.name + "_m");
if(t_m!=null)
{
m.SetTexture("_MetallicGlossMap", t_m);
}
else
{
Debug.Log("材质名:" + o.name + " 材质替换失败,请检查资源");
}
}
}
else
{
m.mainTexture = null;
m.SetTexture("_BumpMap", null);
m.SetTexture("_MetallicGlossMap", null);
}
}
}
}
}
this.ShowNotification(new GUIContent("批量关联材质贴图成功"));
}
else
{
this.ShowNotification(new GUIContent("没有选择游戏对象"));
}
}
static Texture GetTexture(string name)
{
foreach (string suffix in config)
{
Texture t = AssetDatabase.LoadAssetAtPath("Assets/FBX/Textures/" + name + suffix, typeof(Texture)) as Texture;
if (t != null)
return t;
}
return null;
}
}
还有一个是自己写的小测试,创建窗口改物体名字:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class SetName : EditorWindow {
string nameStr = "123";
[MenuItem("Window/ResetName")]
static void Apply()
{
Rect wr = new Rect(0, 0, 500, 500);
SetName window = (SetName)EditorWindow.GetWindowWithRect(typeof(SetName), wr, true, "Reset Name");
}
private void OnGUI()
{
nameStr = EditorGUILayout.TextField("Name: ", nameStr);
this.Repaint();//实时刷新
if (GUILayout.Button("debuglog"))
{
SetNames(true);
}
if (GUILayout.Button("close"))
{
this.Close();
}
}
void SetNames(bool isReady)
{
Debug.Log(nameStr);
}
}