转载请注明出处:http://blog.csdn.net/u010019717
更全的内容请看我的游戏蛮牛地址:http://www.unitymanual.com/space-uid-18602.html
这是在 “Unity Editor Extension” 系列的第 2 次帖子。
post 描述了为创建自定义 inspectors 面板在 Unity 编辑器的基本步骤。在该系列的下一个 posts,我将深入探讨更高级的主题,例如 inspectors 及 Unity’s serialization 系统。
Inspector 检查器基础知识
Inspector 是在 Unity 编辑器 — — 单一视图,显示一个游戏物体的所有相关信息,允许轻松地操纵它的最常用的窗口之一。
默认情况下,检查器允许编辑任何可以被序列化的,根据这些规则(请参见这篇文章):
◾Public, or marked with[SerializeField]
◾Not static
◾Not const, readonly
◾Field of a type that canbe serialized
你可能会问自己,字段可以是序列化?:
◾Custom non abstractclasses with [Serializable] attribute.
◾Custom structs with[Serializable] attribute. (new in Unity4.5)
◾Objects that derive fromUntiyEngine.Object
◾Primitive data types(int, float, double, bool, string, etc)
◾Arrays of a type that canbe serialized
◾List
创建自定义的检查器
Unity 允许创建自定义的检查器为您定义的自定义类。这可以出于各种原因,例如:自定义检查器看起来或自动化(做一些字段的值发生更改时)某一特定行为。
若要创建一个新的 inspector,首先创建一个新的 editor 类 (代码文件放置在一个 Editor 中的文件夹),并从中 Editor 类派生。此类应该也可饰用 CustomEditor 属性,以便让引擎知道哪种类型的编辑器用来:
[CustomEditor(typeof(MySettingsClass))]
publicclassMySettingsEditor : Editor
{
publicoverridevoidOnInspectorGUI()
{
// This is where the magic happens.
}
}
重写方法 OnInspectorGUI 是提供 GUI 代码显示检查器的内容。这篇文章并不处理的创作 GUI 元素以及如何风格新 inspector — — 这些主题都计划在将来的文章覆盖。
显示默认检查器
有时你可能想要保持原 inspector 时仅向其添加次要更改外观。这可以使用 DrawDefaultInspector 方法。例如,请考虑将 “Reset” 按钮添加到 Transform 组件:
[CustomEditor(typeof(Transform))]
publicclassTransformEditor : Editor
{
publicoverridevoidOnInspectorGUI()
{
if(GUILayout.Button("Reset"))
{
vartransform = target asTransform;
transform.position = Vector3.zero;
transform.localScale = Vector3.zero;
transform.rotation = Quaternion.identity;
}
// This draws the default inspector for MySettingsClass
DrawDefaultInspector();
}
}
上面的代码的结果可以看到在下边。你可以看到一个新的 “Reset” 按钮被添加在 Transform’s inspector。
注: 默认 inspector 是一个通用的实现并不可能是你已经习惯了 !例如,变换组件具有内部实现完全一样 (源于编辑器和装饰用 CustomEditor 属性) 上文所述的 UnityEditor.dll,一个内置的自定义实现。不幸的是,如果你想要重写,而不是默认的督察,要诉诸反射来调用该检查方法。
示例用法 — — 执行自定义代码检查器获取修改时
在此示例中,每当在检查器 GUI 变化,自定义代码将执行,并打印被修改的对象到控制台:
usingUnityEngine;
[CustomEditor(typeof(MonoBehaviour), true)]
publicclassMonoBehaviourPropertiesEditor : Editor
{
publicoverridevoidOnInspectorGUI()
{
// Draw the default inspector first.
DrawDefaultInspector();
if(GUI.changed)
{
OnModified();
}
}
privatevoidOnModified()
{
Debug.Log("Inspector modified: " + target.name);
}
}
这是一个相当做作的例子,但这可以真正有价值的用途。在我们的项目,例如,我们有检查器允许您选择用于编辑对象的 “mode”。一旦选择模式,则调用方法时(以同样的方式,如上所示),更改该对象的可视状态,使其匹配的新的模式,使所做的更改立即在场景视图中可用。
摘要
我们已经看到如何创建自定义的检查器的自定义类 (inspectors 不只用来编辑 MonoBehaviours,他们可以编辑任何可序列化的资源如 ScriptableObjects)。