Search Unity

Custom Inspector: Toogle Elements via Enum Selection

Discussion in 'Immediate Mode GUI (IMGUI)' started by Sandler, Apr 21, 2016.

  1. Sandler

    Sandler

    Joined:
    Nov 6, 2015
    Posts:
    241
    I have an enum FruitType A, B, C.

    Now i have the classes FruitProperties:
    FruitA, FruitB, FruitC.


    My monobehaviour has a lots of data, somewhere in its substructure there is the FruitDataClass:

    Properties ->
    Properties ->
    FruitDataClass

    public FruitType fruitType;
    public FruitA fruitDataA;
    public FruitB fruitDataB;
    public FruitC fruitDataC;


    That solution is really bad practice.. i know .. but how on earth can i hide FruitA & FruitB if FruitC is selected, without writing a complete custom editor.

    //CustomPropertyDrawer
    I wrote a custom property drawer, that does this, but how can i tell it to auto size those fields.

    Am i missing something really basic - or is this just bad by design. Took me two hours, to get nowhere.
     
  2. skalev

    skalev

    Joined:
    Feb 16, 2012
    Posts:
    264
    Well, first it does seem like a bad design :) but without knowing your entire code / reasoning I can't really give any advice there.

    In any case, you can write a custom property drawer, which you'll apply to each Fruit class property. It will recieve as a parameter, the name of the fruit enum field, and the type of the fruit it is. so your code will look like this:

    Code (CSharp):
    1. public FruitType fruitType;
    2. [MyPropertyAttribute("fruitType" , FruitType.TypeA)]
    3. public FruitA fruitDataA;
    4. [MyPropertyAttribute("fruitType" , FruitType.TypeB)]
    5. public FruitB fruitDataB;
    6. [MyPropertyAttribute("fruitType", FruitType.TypeC)]
    7. public FruitC fruitDataC;
    Next, in your property drawer itself, inside OnGUI, you use the reference to the serializedObject (from the passed in SerializedProperty parameter), to find the value of "fruitType" property, and check if the type defined in your attribute equals the current value of "fruitType". If so you draw the property. If not, you don't. You can do the same trick in GetPropertyHeight, and return 0 when you shouldn't draw, so that you get a nice condensed inspector.