自定義編輯器 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 就使得編輯模式下移動 MainCamera 會總是朝著(0,0,0)贞盯;而去掉就不會杠氢。
創(chuàng)建自定義編輯器
默認(rèn)情況下昂勉,上面示例的腳本組件在 Inspector 中如下圖的式樣。
默認(rèn)式樣
這些功能都不錯宪睹,但我們還可以使 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 這個組件具有自定義編輯器功能亭病。具體在 Inspector 中自定義的外觀在 OnInspectorGUI() 中定制鹅很。這里僅使用了Vector3 的默認(rèn)布局外觀,并在下方添加一個 Label 表明當(dāng)前位置在 lookAtPoint 的上方還是下方罪帖。我們在看看 MainCamera 的 Inspector促煮,變成了如下的式樣。
場景視圖擴(kuò)展
與上面類似胸蛛,我們通過在 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 出現(xiàn)一個可以控制和拖拽的點(diǎn)泞当,并且移動它,攝像頭的朝向也跟隨著改變民珍。Inspector 中的數(shù)值也隨之改變襟士。
Scene視圖