【Unity】【エディタ拡張】配列のSerializedPropertyの子要素を最後まで回す正しい方法

Unityで配列のSerializedPropertyの子要素を最後まで回す方法が調べづらくハマりやすいのでまとめました。

Unity2021.3.16f1

方法

タイトルのままなのでいきなりコードを書きます。
ポイントはコメントに記載しています。

using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(Example))]
public sealed class ExampleEditor : Editor
{
    public override void OnInspectorGUI()
    {
        var property = serializedObject.FindProperty("items.Array");
        
        // 最後のプロパティはGetEndPropertyで取得できる
        var endProperty = property.GetEndProperty();

        // 最初の子を展開(この最初の一回だけ引数をtrueにする必要がある)
        property.NextVisible(true);

        while (property.NextVisible(false)) // 子がなくなるまでループ
        {
            // 最後の要素の到達したら終了
            // SerializedProperty同士はEqualContentsで比較
            if (SerializedProperty.EqualContents(property, endProperty))
                break;

            // プロパティが配列サイズかどうかはpropertyTypeで判定できる
            // 配列サイズプロパティを描画などに使わない場合はスキップしたり
            if (property.propertyType == SerializedPropertyType.ArraySize)
                continue;
        }
    }
}

参考

docs.unity3d.com