Search code examples
c#fieldinfo

GetValue() from a variable field inside a class


Suppose I have a simple class:

 public class TestScript : MonoBehaviour {
      public Vector3 myVector3;
 }

Now I want to iterate through an the fields of an instance of this class and to access the fields of this field (Field-Ception!) and assign the values to variables of the right Type, effectively "wrapping" the field so it can be serialized. Here, I would reach the Vector3 field "myVector3" and upon reaching it, go over it's fields and assign their Values to three floats (what a Vector3 is made up of).

Problem? fieldinfo.GetValue() returns the Type MonoField! If I use fieldinfo.FieldType, it returns Vector3, but that doesn't help me as I need the Value :/

TestScript myTestScript;//an instance of the MonoBehaviour class
const BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
 //the fields... only 1 in this case (myVector3)
 FieldInfo[] fields = myTestScript.GetType().GetFields(flags);

 //store Type...
 var tp = myTestScript.GetType();
 //iterate over the fields
 foreach FieldInfo field in fields) {

      if (field != null) {
           //check if the field is of Type Vector3
           if(field.FieldType == typeof(Vector3)) {
                const BindingFlags flags_v3 = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
                //the following will give me an array of FieldInfo 
                //with Type MonoField, but I need the 
                //actual x, y and z (floats) fields!
                FieldInfo[] fields_v3 = field.GetType().GetFields(flags);
                //added with edit:
                foreach(FieldInfo field_v3 in fields_v3) {
                    object value = field_v3 .GetValue(field)//the line in question... Since field.GetType returns MonoFields instead of the Vector3, I can not access the Vector3 Type's x y z fields/values.
                }
           }
      }
 }

Solution

  • field.GetType() returns the type of the actual reflection object, which is MonoField, in this case. Use field.FieldType, this property contains the type of the value stored in the field itself:

    FieldInfo[] fields_v3 = field.FieldType.GetFields(flags);