Unity編輯器拓展(三) Custom Editors

官方文檔
Unity編輯器拓展(一)
Unity編輯器拓展(二)
Unity編輯器拓展(三)

自定義編輯器 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視圖
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容