うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】SerializedProperty を用いたクラス描画手法 ~1~

SerializedProperty の表示

通常 SerializedProperty を利用して Editor の表示を行う場合以下ように記述する。

using UnityEditor;

public class SampleEditor : Editor
{
    private SerializedProperty _sampleProp;
 
    private void OnEnable()
    {
        _sampleProp = serializedObject.FindProperty("sample");
    }
 
    public override void OnInspectorGUI()
    {
        EditorGUILayout.PropertyField(_sampleProp, true);
    }
}

SerializedObject 全体を表示

Editor の OnInspectorGUI でも記述されているが SerializedObject 全体を表示する場合は以下のように記述する

public void DrawDefaultInspector(SerializedObject obj)
{
    SerializedProperty iterator = serializedObject.GetIterator();
    for (bool enterChildren = true; iterator.NextVisible(enterChildren); enterChildren = false)
    {
        using (new EditorGUI.DisabledScope("m_Script" == iterator.propertyPath))
            EditorGUILayout.PropertyField(iterator, true);
    }
}

Rect を用いた SerializedObject 全体を表示

public bool DrawDefaultInspector(SerializedObject obj, Rect position)
{
    SerializedProperty iterator = serializedObject.GetIterator();
    for (bool enterChildren = true; iterator.NextVisible(enterChildren); enterChildren = false)
    {
        using (new EditorGUI.DisabledScope("m_Script" == iterator.propertyPath))
        {
            position.height = EditorGUI.GetPropertyHeight(iterator);
            EditorGUI.PropertyField(rect, iterator, true);
            position.y += position.height;
        }
    }
}

SerializedProperty 以下のみを全表示

depthのチェックを追加、途中の SerializedProperty からやった場合その SerializedProperty が終わっても処理が行われるため

serializedObject.GetIterator() のような場合は親から取得するので表示は変わらない

public void DrawPropertyOnly(SerializedProperty property)
{
    var depth = property.depth;
    var iterator = property.Copy();
    for (var enterChildren = true; iterator.NextVisible(enterChildren); enterChildren = false)
    {
        if (iterator.depth < depth)
            return;
 
        depth = iterator.depth;
 
        using (new EditorGUI.DisabledScope("m_Script" == iterator.propertyPath))
            EditorGUILayout.PropertyField(iterator, true);
    }}