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!
Aucun commentaire:
Enregistrer un commentaire