自定义编辑器 Custom Editors
通过自定义编辑器,可以让我们的游戏开发更高效。
ExecuteInEditMode
ExecuteInEditMode 可以让你在编辑模式下就能执行你的脚本。例如如下示例:
新建脚本 LookAtPoint.cs 并拖拽到 MainCamera 上。
[ExecuteInEditMode]
public class LookAtPoint : MonoBehaviour {
public Vector3 lookAtPoint = Vector3.zero;
void Update() {
transform.LookAt(lookAtPoint);
}
}
加上 ExecuteInEditMode 就使得编辑模式下移动 MainCamera 会总是朝着(0,0,0);而去掉就不会。
创建自定义编辑器
默认情况下,上面示例的脚本组件在 Inspector 中如下图的式样。
这些功能都不错,但我们还可以使 Unity 工作的更好。我们通过在 Editor/ 下创建 LookAtPointEditor.cs 脚本。
[CustomEditor(typeof(LookAtPoint))]
[CanEditMultipleObjects]
public class LookAtPointEditor : Editor {
SerializedProperty lookAtPoint;
void OnEnable() {
// 获取到 lookAtPoint 成员属性
lookAtPoint = serializedObject.FindProperty("lookAtPoint");
}
public override void OnInspectorGUI() {
serializedObject.Update();
EditorGUILayout.PropertyField(lookAtPoint);
if (lookAtPoint.vector3Value.y > (target as LookAtPoint).transform.position.y) {
EditorGUILayout.LabelField("(Above this object)");
}
if (lookAtPoint.vector3Value.y < (target as LookAtPoint).transform.position.y) {
EditorGUILayout.LabelField("(Below this object)");
}
serializedObject.ApplyModifiedProperties();
}
}
LookAtPointEditor 继承自 Editor, CustomEditor 告诉 Unity 这个组件具有自定义编辑器功能。具体在 Inspector 中自定义的外观在 OnInspectorGUI() 中定制。这里仅使用了Vector3 的默认布局外观,并在下方添加一个 Label 表明当前位置在 lookAtPoint 的上方还是下方。我们在看看 MainCamera 的 Inspector,变成了如下的式样。
场景视图扩展
与上面类似,我们通过在 OnSceneGUI 中定制我们在 Scene 中的功能。接着上面的示例来,我们添加如下代码:
public void OnSceneGUI() {
LookAtPoint t = (target as LookAtPoint);
EditorGUI.BeginChangeCheck();
Vector3 pos = Handles.PositionHandle(t.lookAtPoint, Quaternion.identity);
if (EditorGUI.EndChangeCheck()) {
Undo.RecordObject(target, "Move point");
t.lookAtPoint = pos;
t.Update(); // 需要把 LookAtPoint.cs 中 Update 改为 public 的
}
}
如图所示,在 Scene 出现一个可以控制和拖拽的点,并且移动它,摄像头的朝向也跟随着改变。Inspector 中的数值也随之改变。