using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MaterialScriptTest))]
public class MaterialInspectorEditor : Editor {
public override void OnInspectorGUI()
{
DrawDefaultInspector();
MaterialScriptTest myScript = (MaterialScriptTest)target;
if (GUILayout.Button ("Apply"))
{
PrefabType pType = PrefabUtility.GetPrefabType(myScript.gameObject);
Object obj = PrefabUtility.GetPrefabObject (myScript.gameObject);
if (pType != PrefabType.PrefabInstance)
{
return;
}
//获取预制件根结点
GameObject prefabInstance = GetPrefabInstanceParent(myScript.gameObject, obj);
if (prefabInstance != null)
{
//获取到预制件Asset
Object prefabAsset = PrefabUtility.GetPrefabParent (prefabInstance);
if (prefabAsset != null)
{
//TODO: 除脏数据(恢复Material为真正的Material)
myScript.Clear();
//使用Instance更新预制件asset
PrefabUtility.ReplacePrefab (prefabInstance, prefabAsset, ReplacePrefabOptions.ConnectToPrefab);
}
}
AssetDatabase.SaveAssets ();
}
}
GameObject GetPrefabInstanceParent(GameObject obj, Object prefabObj)
{
Transform parent;
while (true)
{
parent = obj.transform.parent;
if (parent == null || !PrefabUtility.GetPrefabObject (parent.gameObject).Equals (prefabObj))
return obj;
obj = parent.gameObject;
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class MaterialScriptTest : MonoBehaviour {
[Range(1,100)]
public int intParm = 1;
private Material mat;
// Use this for initialization
void Start () {
mat = GetComponent<SpriteRenderer>().sharedMaterial;
GetComponent<SpriteRenderer>().material = mat;
}
// Update is called once per frame
void Update () {
mat.SetInt ("_IntParm", intParm);
}
void OnDestroy(){
Debug.Log ("Destroy()");
mat = null;
}
public void Clear(){
}
}
d
修改Sprite2之后点击Apply会调用Editor的代码,进行对SpriteRoot预制件进行Apply(废话很少对吧)
d d