Unity编辑器开发分享Unity技术分享征服Unity3d

Unity PropertyDrawer做泛型可排序列表

2016-03-31  本文已影响880人  2b75747cf703

http://va.lent.in/unity-make-your-lists-functional-with-reorderablelist

using System.Collections.Generic;

public class ReorderableListBase { }

public class ReorderableList<T> : ReorderableListBase
{
    public List<T> List;
}
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;

[CustomPropertyDrawer(typeof(ReorderableListBase), true)]
public class ReorderableListDrawer : PropertyDrawer
{
    private ReorderableList _list;

    private ReorderableList GetReorderableList(SerializedProperty property)
    {
        if (_list == null)
        {
            var listProperty = property.FindPropertyRelative("List");

            _list = new ReorderableList(property.serializedObject, listProperty, true, true, true, true);

            _list.drawHeaderCallback += delegate (Rect rect)
            {
                EditorGUI.LabelField(rect, property.displayName);
            };

            _list.drawElementCallback = delegate (Rect rect, int index, bool isActive, bool isFocused)
            {
                EditorGUI.PropertyField(rect, listProperty.GetArrayElementAtIndex(index), true);
            };
        }

        return _list;
    }


    public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    {
        return GetReorderableList(property).GetHeight();
    }


    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        var list = GetReorderableList(property);

        var listProperty = property.FindPropertyRelative("List");
        var height = 0f;
        for (var i = 0; i < listProperty.arraySize; i++)
        {
            height = Mathf.Max(height, EditorGUI.GetPropertyHeight(listProperty.GetArrayElementAtIndex(i)));
        }

        list.elementHeight = height;
        list.DoList(position);
    }
}
using System;
using UnityEngine;

[Serializable]
public class ReorderableVector3List : ReorderableList<Vector3>
{

}

[Serializable]
public class ReorderableColorList : ReorderableList<Color>
{

}

public class ReorderableListTest : MonoBehaviour
{
    public ReorderableVector3List vector3;
    public ReorderableColorList color;

    // Use this for initialization
    void Start ()
    {

    }

    // Update is called once per frame
    void Update ()
    {

    }
}
Paste_Image.png
上一篇下一篇

猜你喜欢

热点阅读