Show and hide serialized class fields based on enum values?

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 of there:

[System.Serializable]
public class Item
{
    // enum to set item type
    public ItemType itemType;

    // weapon
    public int damage;
    // more fields for weapon
    // ...
 
    // food
    public int foodPoints;
    // more food fields
    // ...
 
    // armor
    public int armorPoints;
    // more armor fields
    // ...
}

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?

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:

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.

1 Like