- Home /
Iterate through object fields
I'm making an in game editor for my buildings, and I need to iterate through the building class's fields to instanciate fields to edit each property.
The fields are prefab, my buildings class has a number of fields that can vary in the future, and I'd like to make an editor that instanciates one inputField for each field I can edit.
How can I iterate through all fields ? I tried something like :
foreach (var thisVar in building.GetType().GetProperties())
{
Debug.Log("Var Name : " + thisVar.Name +
" ; Type : " + thisVar.PropertyType +
" ; Value : " + thisVar.GetValue(building, null));
}
but nothing appears in the console (and I am absolutely not sure about the usage of getValue()).
Can anyone give a hand ? :D
EDIT: Thanks to @Kciwsolb, I now know the code loops through attributes, and I have none. I like the idea of Scriptable Objects, but it doesn't solve the fact that I don't know the number of fields I might have in the future...
Normally people would make scriptable object to hold information and use it for Editor not find property in script.
Also check if building is null if building is empty then your editor did not find "Target"
Also, place another Debug.Log with some random test string to see if you're at least looping through it. Then if you know you're in the loop, also Debug.Log(thisVar) to what you're getting back.
Answer by Kciwsolb · Jun 04, 2018 at 01:16 PM
It is possible you do not have any properties in your class. Are you sure you have properties and not just public fields? I have seen people confuse the terms so it is worth asking. A property is a special method for accessing private fields. Here is an example:
//This is a private field:
private string name;
//This is a property:
public string Name
{
get{ return name; }
set{ name = value; }
}
//This is just a public field:
public string alternateName;
Just making sure. If for some reason you were not using properties, here is the documentation on them.
Otherwise try just doing a Debug.Log(thisVar.ToString());
in your loop to see if it is working.
Indeed I'm using fields, because I serialize the class to json so they need to be public fields. I'll edit the question to use proper vocabulary.
Just use GetFields() ins$$anonymous$$d of GetProperties then.
Works like a charm, thank you very much !
Your answer
