0

I am trying to create a class with many public members. The number is large, so I don't want to print them one by one. Therefore, I want to use C# build-in functions to print out all member names and its value. The approach I tried was to use type.GetMembers() to get MemberInfo, which allowed me to get all of the member names. However, I still can't get values. The following is my source code:

public class Unit : Card
{
    // ... a bunch of public members
    public string name;
    // ... more
    // ...

    public void print()
    {
            Debug.Log("CARD INFO \"" + name + "\":\n");

            Type type = typeof(Unit);
            MemberInfo [] members = type.GetMembers();

            foreach(var member in members)
            {
                FieldInfo field = type.GetField(member.Name);
                Debug.Log(member + ": " + field.GetValue(this) );
            }

     }
}

This script is used by Unity, Debug.Log() is just used to output strings. The error I get is "Object reference not set to an instance of an object", referring to the last line of code. So I am guessing it could be due to the use of this. Any help is appreciated!

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
  • 3
    Not all members are fields. – Theraot Jan 28 '20 at 01:26
  • Not all members even have _values_. Your question is not _about_ Unity3d in any way, so I've removed those tags. See marked duplicate for how to restrict the members you get to just those which are fields, so that `GetField()` will return a value. Alternatively, just check for `null` and don't try to get the value from a `FieldInfo` object reference that's set to `null`. – Peter Duniho Jan 28 '20 at 01:37

0 Answers0