Search Unity

Question Dynamicly creating correct type input fields for all objects variables

Discussion in 'UI Toolkit' started by beneQ_04, Jun 1, 2023.

  1. beneQ_04

    beneQ_04

    Joined:
    Mar 1, 2020
    Posts:
    21
    So I am trying to make a custom editor window and as a part of that I need to be able to input some varaibles into my objects. The problem is I need it to be dynamic. So I need to be able to pass in any object and from that generate all of the correct type input fields for this object and display them.

    I know how to get all of the objects fields into a list with reflection, the problem is now how do I generate the correct types of fields with this list?

    What I have made so far is just check for a type of the varaiable and craete a corresponding input field to that so for example:
    Code (CSharp):
    1.  
    2. if (type == typeof(int))
    3. {
    4.          IntegerField field = new IntegerField(variable.Name);
    5.          field.value = (int)varaible.GetValue(myObject);
    6.          myVisualElement.Add(field);
    7.          field.RegisterValueChangedCallback(evt => { varaible.SetValue(myObject, field.value); });
    8. }
    9.  
    But this is terrible as I have to repeat that code for every type.

    Ideally I would want to just make a generic field and just do field.Set Type(type) or something like that.