【Unity】デフォルトで配列とListを並び替え可能にするエディタ拡張【ReorderableList】

<blockquote class="twitter-tweet"><p lang="ja" dir="ltr"><a href="https://t.co/UV7XdLWg9z">https://t.co/UV7XdLWg9z</a><br><br>入れるだけで配列とListをReorderableにしてくれるエディタ拡張作った。<br><br>Odinみたいに簡単にカスタマイズとかできないけど、素のUnityの状態よりはマシかな。 <a href="https://t.co/PLONGK4Avx">pic.twitter.com/PLONGK4Avx</a></p>&mdash; su10@ハイパーカジュアルゲーム開発 (@su10_dev) <a href="https://twitter.com/su10_dev/status/1318526359187025920?ref_src=twsrc%5Etfw">October 20, 2020</a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

<font color="red">
ーー 2020/10/22追記 ーー

`ScriptableObject`を選択したときに表示がバグる不具合を確認したので直るまで使用しないでください。
というかQiitaって記事を公開したら限定公開にできないのね。。

ーー 追記ここまでーー

# はじめに
[Odin](https://assetstore.unity.com/packages/tools/utilities/odin-inspector-and-serializer-89041) を入れると自動で配列や`List`が並び替え可能かつ様々な拡張が可能になって便利なのですが、Odinは最近ライセンスが変更されて会社利用しにくくなりました（詳細は[Pricingのページ](https://odininspector.com/pricing)参照）。

[コガネブログ様の記事](https://baba-s.hatenablog.com/entry/2020/09/16/090000)によるとUnity2020.2bからはデフォルトで配列や`List`がReorderableになるらしいのですが、OdinなしのUnity2019でも特別な対応無しで並べ替え可能にしたかったのでいろいろ調べました。

# ソースコード
[Gist](https://gist.github.com/su10/72af707c77b2be98040adf10f588440d)にも載せてますが、大して長くもないので全文掲載しておきます。適当に `Assets/Editor/` とかに入れると自動で適用されます。配列・`List`側がクラスを継承したり特別な属性を付与する必要もありません。

コードは[こちら](https://github.com/andeart/UnityLabs.ReorderableListEditor)を元にUnity2019で表示がおかしかったのを修正＆リファクタリングしたものです。

```ReorderableListEditor.cs
/*
MIT License

Copyright (c) 2018 ANURAG DEVANAPALLY

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#if UNITY_EDITOR
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;

// SEE: https://github.com/andeart/UnityLabs.ReorderableListEditor
namespace Andeart.ReorderableListEditor
{
    /// <summary>
    /// Custom editor to allow re-orderable lists/arrays in Unity Inspector automatically.
    /// This custom editor overrides Unity's default SerializedProperty drawing for arrays and lists.
    /// This is inspired by Valentin Simonov's blog article here:
    /// http://va.lent.in/unity-make-your-lists-functional-with-reorderablelist/ , along with additional tweaks/functionality.
    /// </summary>
    /// <inheritdoc />
    [CustomEditor(typeof(Object), true)]
    [CanEditMultipleObjects]
    public class ReorderableListEditor : Editor
    {
        private Dictionary<string, ReorderableListProperty> _reorderableListDict;

        protected virtual void OnEnable()
        {
            _reorderableListDict = new Dictionary<string, ReorderableListProperty>();
        }

        protected virtual void OnDestroy()
        {
            _reorderableListDict.Clear();
            _reorderableListDict = null;
        }

        public override void OnInspectorGUI()
        {
            var propertyValueColor = GUI.color;
            serializedObject.Update();
            var property = serializedObject.GetIterator();

            if (property.NextVisible(true))
            {
                do
                {
                    GUI.color = propertyValueColor;
                    DrawProperty(property);
                } while (property.NextVisible(false));
            }

            serializedObject.ApplyModifiedProperties();
        }

        private void DrawProperty(SerializedProperty property)
        {
            var isPropertyMonoBehaviourId = property.name.Equals("m_Script")
                                            && property.type.Equals("PPtr<MonoScript>")
                                            && (property.propertyType == SerializedPropertyType.ObjectReference)
                                            && property.propertyPath.Equals("m_Script");

            if (isPropertyMonoBehaviourId)
            {
                EditorGUI.BeginDisabledGroup(true);
                EditorGUILayout.PropertyField(property);
                EditorGUI.EndDisabledGroup();

                return;
            }

            if (property.isArray && property.propertyType != SerializedPropertyType.String)
            {
                this.DrawListProperty(property);
            }
            else
            {
                EditorGUILayout.PropertyField(property, property.isExpanded);
            }
        }

        private void DrawListProperty(SerializedProperty property)
        {
            var reorderableListProperty = this.GetReorderableList(property);

            if (reorderableListProperty.property.isExpanded == false)
            {
                reorderableListProperty.DoListHeader();
            }
            else
            {
                reorderableListProperty.DoLayoutList();
            }

            EditorGUILayout.GetControlRect(true, -2f);
        }

        private ReorderableListProperty GetReorderableList(SerializedProperty property)
        {
            if (_reorderableListDict.TryGetValue(property.name, out var reorderableListProperty))
            {
                reorderableListProperty.property = property;
                return reorderableListProperty;
            }

            reorderableListProperty = new ReorderableListProperty(property);
            _reorderableListDict[property.name] = reorderableListProperty;

            return reorderableListProperty;
        }

        private class ReorderableListProperty
        {
            private const float HeaderLeftMargin = 10f;
            private const float ElementTopMargin = 2f;
            private const float ElementLeftMargin = 9f;
            private const float ElementVerticalMargin = 4f;
            private static readonly FieldInfo ReorderableListDefaultsField = typeof(ReorderableList).GetField("s_Defaults", BindingFlags.Static | BindingFlags.NonPublic);
            private static readonly MethodInfo DoListHeaderMethod = typeof(ReorderableList).GetMethod("DoListHeader", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod);

            private ReorderableList _list;
            private SerializedProperty _property;

            public SerializedProperty property
            {
                get => _property;
                set
                {
                    _property = value;
                    _list.serializedProperty = _property;
                }
            }

            public ReorderableListProperty(SerializedProperty property)
            {
                _property = property;

                _list = new ReorderableList(_property.serializedObject, _property, true, true, true, true);
                _list.drawHeaderCallback += this.OnDrawHeader;
                _list.drawElementCallback += this.OnDrawElement;
                _list.elementHeightCallback += this.OnElementHeight;
                _list.onCanRemoveCallback += this.OnCanRemove;
            }

            ~ReorderableListProperty()
            {
                _property = null;
                _list = null;
            }

            private void OnDrawHeader(Rect rect)
            {
                _property.isExpanded = EditorGUI.Foldout(
                    new Rect(rect.x + HeaderLeftMargin, rect.y, rect.width, rect.height),
                    _property.isExpanded,
                    _property.displayName,
                    true,
                    EditorStyles.foldout
                );
            }

            private void OnDrawElement(Rect rect, int index, bool active, bool focused)
            {
                rect.y += ElementTopMargin;
                rect.height = EditorGUIUtility.singleLineHeight;

                var propertyChild = _property.GetArrayElementAtIndex(index);

                if (propertyChild.propertyType == SerializedPropertyType.Generic)
                {
                    rect.x += ElementLeftMargin;
                    rect.width -= ElementLeftMargin;

                    EditorGUI.LabelField(rect, propertyChild.displayName);
                }

                EditorGUI.PropertyField(rect, propertyChild, GUIContent.none, true);
                _list.elementHeight = rect.height + ElementVerticalMargin;
            }

            private float OnElementHeight(int index)
            {
                return Mathf.Max(
                    EditorGUIUtility.singleLineHeight,
                    EditorGUI.GetPropertyHeight(_property.GetArrayElementAtIndex(index), GUIContent.none, true)
                ) + ElementVerticalMargin;
            }

            private bool OnCanRemove(ReorderableList list)
            {
                return 0 < _list.count;
            }

            public void DoListHeader()
            {
                if (ReorderableListDefaultsField.GetValue(null) == null)
                {
                    ReorderableListDefaultsField.SetValue(null, new ReorderableList.Defaults());
                }

                var rect = GUILayoutUtility.GetRect(0.0f, _list.headerHeight, GUILayout.ExpandWidth(true));
                DoListHeaderMethod.Invoke(_list, new object[] {rect});
            }

            public void DoLayoutList()
            {
                _list.DoLayoutList();
            }
        }
    }
}
#endif
```

# 所感
`[CustomEditor(typeof(Object), true)]` なカスタムエディタを書けばデフォルトのInspector表示も変更できるの知らなかった。

# 参考
* [UnityLabs.ReorderableListEditor](https://github.com/andeart/UnityLabs.ReorderableListEditor)
* [Unity: make your lists functional with ReorderableList](https://va.lent.in/unity-make-your-lists-functional-with-reorderablelist/)
* [【Unity】【エディタ拡張】ReorderableListの使い方](https://light11.hatenadiary.com/entry/2019/04/13/233049)（LIGHT11）
* [ReorderableListのすすめ - Synamon's Engineer blog](https://synamon.hatenablog.com/entry/2019/06/25/190000)
    * カスタムエディタが楽に書けるやつ
* [Reorderable List](https://github.com/cfoulston/Unity-Reorderable-List)
    * Odinみたいに多機能だけどカスタムエディタを書くか継承が必要なやつ