Search Unity

Show and hide serialized class fields based on enum values?

Discussion in 'Immediate Mode GUI (IMGUI)' started by eses, Nov 20, 2019.

  1. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    Hi

    I was thinking about a way to remove clutter from inspector view of a class that is sort of class containing data for multiple item types to avoid inspector serialization issues if I were trying to use sub classes instead.

    Say I have a class similar to one shown below and then a List<Item> of there:
    Code (CSharp):
    1. [System.Serializable]
    2. public class Item
    3. {
    4.     // enum to set item type
    5.     public ItemType itemType;
    6.  
    7.     // weapon
    8.     public int damage;
    9.     // more fields for weapon
    10.     // ...
    11.  
    12.     // food
    13.     public int foodPoints;
    14.     // more food fields
    15.     // ...
    16.  
    17.     // armor
    18.     public int armorPoints;
    19.     // more armor fields
    20.     // ...
    21. }
    22.  
    And I would need to render each list element with custom property drawer I guess.

    So could I be able to somehow only show weapon fields if I've set itemType enum to weapon?

    I remember having issues with item height as showing a different set of fields will change the height of that item in list.

    I have used serialized objects and serialized properties a little bit, but don't remember if this was doable or not.

    Any ideas / help?
     
  2. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    I'll answer this one myself.

    I came to conclusion that I'll either have to:

    Show fields manually based on itemType selection.

    If I selected/set enum to Weapon type, I draw each weapon field manually.... and so on. To make this work in lists, I found some good threads, how to fix list to work with different heights for each list element:

    https://forum.unity.com/threads/custom-property-drawer-in-list-layout-messed-up.563035/
    https://answers.unity.com/questions/528274/variable-property-drawer-height-effects-all-in-lis.html

    Another way is to render each part so that Item class has fields (Weapon, Pickup) that are depicting each item subtype. Then I can use serialized property to draw that class, using EditorGUILayout.PropertyField and its option includeChildren.

    But anyway, if there is some better way to do this I'm all ears.
     
    Last edited: Nov 21, 2019
    skoteskote likes this.