PropertyAttribute for array fields

Hey there,
I’m working on PropertyAttribute which draws custom editor for array of custom class.

I’ve seen in many topics which PropertyAttribute doesn’t support arrays and lists. (In OnGUI function of PropertyDrawer we can’t access to it by property parameter of OnGUI function)
So they suggest using parent class which has that array in itself.

Also I’ve seen this attribute in github. As you see he uses array for his attribute but I’ve not understood how he achieved it.

So at the end using PropertyAttribute for array fields is possible ?

Well if you want to get your Array back from elements of the array you can use:

string path = property.propertyPath;
path = path.Substring(0, path.LastIndexOf('.'));
//Your path should end with Array.data[x], so removing the last part will access the array path
SerializedProperty array = property.serializedObject.FindProperty(path);
3 Likes

Targeting array fields with a PropertyAttribute is not possible, at least not out of the box.

The trick to get around this limitation is to completely replace the default Editor with a custom one that manually draws all fields, along with added support for a new kind of attribute that can target collections unlike the PropertyAttribute.

[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public abstract class CollectionPropertyAttribute : Attribute { }
[CustomEditor(typeof(Object), true), CanEditMultipleObjects]
public class ExtendedEditor : Editor
{
    public override void OnInspectorGUI()
    {
        // insert logic for drawing all serialized fields here
    }
}

So this is by no means an easy thing to pull off.

The cool thing is that if you do go through the trouble of doing this, it makes it possible to create drawers for any attributes, not just PropertyAttributes. My favourite one to add support for is NotNull, which I often use extensively in my code.

2 Likes