在Unity中,当我们在Hierarchy或者Project面板中选择一个对象是,Inspector面板中会显示此对象的属性。很多时候,编写Unity工具的时候都需要扩展一下脚本在Inspector上的显示属性,添加一些按钮或者显示信息。
这时候就需要用到CustomEditor属性了。
1、创建一个ExampleEditor脚本,在类上添加[CustomEditor(typeof(T))]属性,重写OnInspectorGUI方法,用于扩展Inspector。
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(Example))]
public class ExampleEditor : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
Example _example = target as Example;
if (GUILayout.Button("执行Example方法"))
{
_example.LogError();
}
//扩展Inspector
}
}
target就是你所添加的类型T,需要强转为你需要的类型。其他的做法与OGUI类似。
2、创建Example脚本,继承MonoBehaviour,用来挂载到Object上。
using UnityEngine;
[ExecuteInEditMode]
public class Example : MonoBehaviour
{
public void LogError()
{
Debug.LogError("执行Example方法");
}
}
Example中添加你需要处理的数据,或者函数。这样挂载Example在GameObject上,Inspector就可以查看和执行相关的函数了。如果你需要在编辑模式上运行周期函数,还可以在Example上添加[ExecuteInEditMode]属性。运行效果如下图:
官方文档: