[Editor]Get FieldInfo by using an instance of that field

Hi, I’m from a small team that are developing a Reverse Tower Defense / RTS.

This is going to be hard to explain… So I’ll use an example to help:

Let’s say we have the following class:

  public class AClass
  {
        public float fExample1;
  }

Somewhere along editor scripts, we will do something like this (the GetName() instruction is my goal what I’d like, it’s just to help understanding):

  AClass a = (AClass) target;
  FieldInfo field = GetType().GetField(**a.fExample1.GetName()**);
  
  SerializedProperty serProp = serializedObject.FindProperty(field.name);

We want to get a FieldInfo by using an instance of the same field in order to avoid hardcoding.

This way if we rename the field per say to fExample2 my code will refactor to this:

  AClass a = (AClass) target;
  FieldInfo field = GetType().GetField( a.fExample2.GetName() );
  
  SerializedProperty serProp = serializedObject.FindProperty(field.name);

Why avoid the hardcoding if this is already kinda hardcoded?

In my development team we mainly use this for selective attributes. We have a structure for all units and as such, our Towers are also units.

We have several fields in [HideInInspector] and in the Inspector/Drawer, fields like the units they will spawn or the positions from which each tower throws bombs/arrows to you are only shown if the Unit represents a tower.

So unfortunately that’s not strictly possible.

The best alternative I have come up with, which I use in my projects, is that I have an attribute I use to decorate SerializedProperty member variables on Editor classes that inherit from a base editor. At compile time, it scans the assemblies for all Editor classes, checks their fields for SerializedProperty members decorated with this attribute, and confirms that the path specified in the attribute argument is valid for the type being inspected. If there’s a problem, you get an error in the console right away so you can fix it. (All decorated fields are also automatically assigned when the Editor is enabled.)

I’m hoping to actually get something like this into a future release of Unity as I think it could be useful. In the meantime, I have some packages on the AssetStore that include this BaseEditor class if you are curious and want to replicate this sort of thing (e.g., Unity Asset Store - The Best Assets for Game Making)