#FieldInfo.GetValue not working properly in Unity

1 messages · Page 1 of 1 (latest)

bitter trout
#

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";
mystic wharf
#

When does this code run?

bitter trout
mystic wharf
#

okay, so it's after Unity has applied serialized properties

bitter trout
#

Yep

mystic wharf
#

(and these have field initializers anyway)

#

can you share the entire script, just to make sure there aren't any surprises?

bitter trout
#

To be sure, this is printed properly

Debug.Log($"{string1}; {string2}");

// string 1; string 2
#

!code

cold wingBOT
mystic wharf
#

This code doesn't actually display the values stored in instances. Did you remove that?

bitter trout
#

I have sent the whole script

mystic wharf
#

Do you have multiple instances of Test? That would make it possible for you to see the correct output in the console and see incorrect values in the debugger

(although, I'd expect you to have looked at the values of string1 and string2 in the debugger anyway)

bitter trout
#

But, you know...
I have now run the code once more and checked via debugger, and both values seem to be gotten correctly

Also the following print gives the correct result..

Debug.Log($"count: {instances.Count}; instances: {string.Join("; ", instances)};");

// count: 2; instances: string 1; string 2;
#

Even though both values were definitely string.Empty before

#

I am sure I have not changed anything significant

mystic wharf
#

I wonder if [ExecuteAlways] has any bearing here. That would mean that OnEnable() executes in edit mode, and doesn't get executed in play mode

bitter trout
#

I also had this generic method implemented before, and it does work perfectly now too

List<string> strings = ReflectionExtension.FindInstances<string>(this);
mystic wharf
#

hm, i haven't got any other ideas