- Home /
CustomPropertyDrawer issue with arrays
I am trying to create a [ReorderableList] attribute so that arrays and lists marked with it can become reorderable. I have a CustomPropertyDrawer for the attribute. The problem is that the OnGUI() method is called for each element of the array/list, and not only once for the array/list itself. Is it possible to somehow make the OnGUI() method to be called for the array/list itself and not for each element individually?
public class MyMonoBehaviour : MonoBehaviour
{
[ReorderableList]
public List<int> list;
}
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public class ReorderableListAttribute : PropertyAttribute
{
}
[CustomPropertyDrawer(typeof(ReorderableListAttribute))]
public class ReorderableListPropertyDrawer : PropertyDrawer
{
private ReorderableList _reorderableList = null;
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return property.isArray
? GetList(property).GetHeight()
: GetPropertyHeight(property) + GetHelpBoxHeight();
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, label, property);
// property.isArray is never true, because the property is an individual element of the list
if (property.isArray)
{
GetList(property).DoList(position);
}
else
{
string message = typeof(ReorderableListAttribute).Name + " can be used only on arrays or lists";
DrawDefaultPropertyAndHelpBox(position, property, message, MessageType.Warning);
}
EditorGUI.EndProperty();
}
private ReorderableList GetList(SerializedProperty property)
{
if (_reorderableList == null)
{
ReorderableList reorderableList = new ReorderableList(property.serializedObject, property, true, true, true, true)
{
drawHeaderCallback = (Rect rect) =>
{
EditorGUI.LabelField(rect, string.Format("{0}: {1}", property.displayName, property.arraySize), EditorStyles.label);
},
drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) =>
{
var element = property.GetArrayElementAtIndex(index);
rect.y += 1.0f;
rect.x += 10.0f;
rect.width -= 10.0f;
EditorGUI.PropertyField(new Rect(rect.x, rect.y, rect.width, 0.0f), element, true);
},
elementHeightCallback = (int index) =>
{
return EditorGUI.GetPropertyHeight(property.GetArrayElementAtIndex(index)) + 4.0f;
}
};
}
return _reorderableList;
}
}
A lot of people are making a wrapper class that wraps an array inside and they make a reorderable list for the relative serialized property inside the wrapper. That's not how I wanna do it.
I also don't want to create a custom editor
Your answer
Follow this Question
Related Questions
How to properly implement ReorderableList expanding/collapsing in CustomPropertyDrawer? 1 Answer
ArrayList Problem. How to access using index. 1 Answer
Store Variables in Variables? 2 Answers
What do you think of this? List, Vector 3 and Update 1 Answer
Trouble Getting Array List To Display Current Song In Game 0 Answers