Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Dynamicly creating correct type input fields for all objects variables

Discussion in 'Scripting' started by beneQ_04, Jun 3, 2023.

  1. beneQ_04

    beneQ_04

    Joined:
    Mar 1, 2020
    Posts:
    20
    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. if (type == typeof(int))
    2. {
    3.          IntegerField field = new IntegerField(variable.Name);
    4.          field.value = (int)varaible.GetValue(myObject);
    5.          myVisualElement.Add(field);
    6.          field.RegisterValueChangedCallback(evt => { varaible.SetValue(myObject, field.value); });
    7. }

    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.
     
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,833
    If you want input fields for different types to behave differently, then at some level in this process, you're going to need different implementations saying how each type behaves, and some logic that maps each type to the appropriate implementation.

    Using a bunch of ifs seems like a not-unreasonable way to perform that mapping, although you could also do it with a dictionary if you prefer.
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,561
  4. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,043
    If you simply want Unity to autodetect the already serialized fields, use PropertyField