Hey I’m trying to figure out how to get private and protected fields from one of my classes. I know you can :
var _t = GetType().GetFields();
But it only gets fields marked as public. How would I get the rest?
Hey I’m trying to figure out how to get private and protected fields from one of my classes. I know you can :
var _t = GetType().GetFields();
But it only gets fields marked as public. How would I get the rest?
what are you trying to do?
I’m not really sure how to explain it any better. I want my class to check it’s own private and protected fields for an attribute basically.
But that only works if I can get those fields.
Use the GetFields overload with the BindingFlags argument. You definitely want BindingFlags.NonPublic.
See here for the BindingFlags docs and usage examples.
EDIT: @LeftyRighty , your signature is really out of date!
I tried that binding flag already and it doesn’t work. I’ll check out the link in case there’s something I’m missing.
But is there any reason that you can think of that would cause that not to work? heres the code I have.
public void Test (){
foreach (var i in GetType().GetFields (System.Reflection.BindingFlags.NonPublic)) {
Debug.Log (i.Name);
}
}
You also need BindingFlags.Instance.
using System.Reflection;
foreach (FieldInfo fieldInfo in GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
{
Debug.Log(fieldInfo.Name);
}
P.S. Why do you even need to do this…?
Thanks for your answer. That worked
My asset deals in a lot of custom classes that inherit to other custom classes and also deals with a lot of custom serialization stuff. and being able to keep a field private or protected while still being able to be seen by my serialization engine is important (Mostly because most unity classes are non serializable). This way I can serialize what needs to be (using an attribute) and skip certain fields such as GameObject and Vectors. Or in some cases handle it differentlySorry if that’s confusing but it would take an hour to explain the project in more detail
Anyway thanks again