I have the following code to find the instances of type string in my MonoBehaviour.
// public class Test : MonoBehaviour
List<string> instances = new();
Type type = GetType();
foreach (FieldInfo field in type.GetFields())
{
if (typeof(string).IsAssignableFrom(field.FieldType))
{
object fieldValue = field.GetValue(this); // string.Empty
if (fieldValue is string instance)
{
instances.Add(instance);
}
}
}
It does work fine when running from a Console App, but in Unity, the FieldInfos are found, but GetValue returns string.Empty for both strings below.
public string string1 = "string 1";
public string string2 = "string 2";