Unable to get the FieldInfo's value
The following method should find the fields of type
T in the class.When having these
strings, it only returns a List of 2 empty ones.TstringsListpublic static List<T> FindInstances<T>(object value)
{
List<T> instances = new();
Type type = value.GetType();
foreach (FieldInfo field in type.GetFields())
{
if (typeof(T).IsAssignableFrom(field.FieldType))
{
object fieldValue = field.GetValue(value);
if (fieldValue is T instance)
{
instances.Add(instance);
}
}
}
return instances;
}public string string1 = "string 1";
public string string2 = "string 2";
type.GetFields(BindingFlags.Instance | BindingFlags.Public) but I'm not 100%, I try to avoid reflection in UnityGetValue returns the empty string in Unity. I'll try to research this thing. Thank you a lot for your help!type.GetFields(BindingFlags.Instance | BindingFlags.Public)GetValuestringforeach (var inst in FindInstances<string>(new FooBar()))
{
WriteLine(inst);
}
static List<T> FindInstances<T>(object value)
{
List<T> instances = new();
Type type = value.GetType();
foreach (FieldInfo field in type.GetFields())
{
if (typeof(T).IsAssignableFrom(field.FieldType))
{
object fieldValue = field.GetValue(value);
if (fieldValue is T instance)
{
instances.Add(instance);
}
}
}
return instances;
}
class FooBar
{
public string foo = "foo";
public string bar = "bar";
}