Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

PropertyAttribute for array fields

Discussion in 'Immediate Mode GUI (IMGUI)' started by a-t-hellboy, Apr 17, 2019.

  1. a-t-hellboy

    a-t-hellboy

    Joined:
    Dec 6, 2013
    Posts:
    180
    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 ?
     
  2. Ciryus

    Ciryus

    Joined:
    Sep 17, 2012
    Posts:
    38
    Well if you want to get your Array back from elements of the array you can use:

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

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,297
    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.
    Code (CSharp):
    1. [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
    2. public abstract class CollectionPropertyAttribute : Attribute { }
    Code (CSharp):
    1. [CustomEditor(typeof(Object), true), CanEditMultipleObjects]
    2. public class ExtendedEditor : Editor
    3. {
    4.     public override void OnInspectorGUI()
    5.     {
    6.         // insert logic for drawing all serialized fields here
    7.     }
    8. }
    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.
     
    markoal likes this.