自定義編輯器 Custom Editors
通過自定義編輯器,可以讓我們的游戲開發(fā)更高效。
ExecuteInEditMode
ExecuteInEditMode 可以讓你在編輯模式下就能執(zhí)行你的腳本。例如如下示例:
新建腳本 LookAtPoint.cs 并拖拽到 MainCamera 上。
[ExecuteInEditMode]
public class LookAtPoint : MonoBehaviour {
public Vector3 lookAtPoint = Vector3.zero;
void Update() {
transform.LookAt(lookAtPoint);
}
}
加上 ExecuteInEditMode 就使得編輯模式下移動(dòng) MainCamera 會(huì)總是朝著(0,0,0);而去掉就不會(huì)。
創(chuàng)建自定義編輯器
默認(rèn)情況下,上面示例的腳本組件在 Inspector 中如下圖的式樣。
默認(rèn)式樣
這些功能都不錯(cuò),但我們還可以使 Unity 工作的更好。我們通過在 Editor/ 下創(chuàng)建 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 這個(gè)組件具有自定義編輯器功能。具體在 Inspector 中自定義的外觀在 OnInspectorGUI() 中定制。這里僅使用了Vector3 的默認(rèn)布局外觀,并在下方添加一個(gè) Label 表明當(dāng)前位置在 lookAtPoint 的上方還是下方。我們?cè)诳纯?MainCamera 的 Inspector,變成了如下的式樣。
場景視圖擴(kuò)展
與上面類似,我們通過在 OnSceneGUI 中定制我們?cè)?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 出現(xiàn)一個(gè)可以控制和拖拽的點(diǎn),并且移動(dòng)它,攝像頭的朝向也跟隨著改變。Inspector 中的數(shù)值也隨之改變。
Scene視圖