Is there any way to do the following:
- Get ALL the components in an object
- Get ALL the variables in a component
- print the variables out
Thanks!
Is there any way to do the following:
Thanks!
I’ve actually been doing stuff like this quite a bit recently, so I have this snippet lying around.
import System.Reflection;
function Start() {
var allMBs : Array = gameObject.GetComponents(MonoBehaviour);
for (m=0;m<allMBs.length;m++) {
var fields : FieldInfo[] = allMBs[m].GetType().GetFields();
for (f=0;f<fields.length;f++) {
Debug.Log("The field named "+ fields[f].ToString() + " contains the value " + fields[f].GetValue(allMBs[m]).ToString());
}
}
}
thanks for that. here is what i did.
I added a ‘plane’ to my scene. stripped it off every component except the transform component. added a script called ‘getparams.js’ with the code above to the ‘plane’. I seem to get the following error:
Assets/getparams.js(9,106): BCE0017: The best overload for the method 'System.Reflection.FieldInfo.GetValue(Object)' is not compatible with the argument list '(Object, null)'.
Sorry, I noticed that shortly after I posted it and edited, but apparently not quite shortly enough. The null on that function call should not be there. (I got it mixed up with SetValue, which does take an extra parameter which is usually ‘null’)
thanks for that. looks like the logic works. however i noticed that GetFields( ) returns ONLY the public members. Hence i have difficulty trying to print something as simple as Transform.position. Can you suggest a way to go around this problem?
Thanks!
Specifically I am unable to figure out the access modifier of Transform.position ( say ) to set the BindingFlag that is appropriate to it.
Transform.position is public.
If it doesn’t show up with GetField() I guess it’s actually a property. So use GetProperty() instead of GetField().
thanks for all the help. here is a working code.
import System.Reflection;
function Start() {
var allMBs : Array = gameObject.GetComponentsInChildren( Component );
for (m=0;m<allMBs.length;m++) {
print(allMBs[m]);
var fields : PropertyInfo[] = allMBs[m].GetType().GetProperties( BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
for (f=0;f<fields.length;f++) {
Debug.Log("The field named "+ fields[f].ToString() + " contains the value " + fields[f].GetValue(allMBs[m], null).ToString());
}
}
}