- Home /
How do I find the name and value for each variable of a script component, using Unity script?
DaveA asked a question "Is there a way to enumerate fields (name/value) on any Component?" and in his description, he stated...
"I found a way to get all components on a GameObject. If those components happen to be Scripts, I can easily find the name/type/value for each field. Great."
But didnt explain how this was achieved, and he's using c# anyway. Could someone explain how to do this in Unity script please. Is it even possible?
Thanks, Glen
Enumerating the fields, methods, etc. of a class is certainly possible; I don't have an example handy at the moment, but look up 'c# reflection' for more info. (Or maybe someone will post some example code for you.)
Answer by Mike 3 · Oct 27, 2010 at 04:23 PM
The page you linked has an example of how to use it, you just need to use javascript syntax for the loops
e.g.
for (var script in GetComponents.<MonoBehaviour>()) { for(var mi : MemberInfo in script.GetType().GetMembers()) Debug.Log(System.String.Format("{0} = {1}", mi.Name, mi.MemberType));
for(var pi : PropertyInfo in c.GetType().GetProperties())
Debug.Log(System.String.Format("{0} = {1}", pi.Name, pi.GetValue(c, null)));
}
Will give you the members and properties on the scripts attached to the current object - you can look up FieldInfo and the rest of the reflection items on MSDN
You'll need to use import System.Reflection; at the top of your script for the above to work
Answer by Glenno · Oct 29, 2010 at 09:35 AM
Hey all, thanks for your reply Mike. This is the code that ended up working. Yours still has some c# syntax in it doesnt it?
for (var script in GetComponents(MonoBehaviour)){ for(var mi : MemberInfo in script.GetType().GetMembers()) Debug.Log(System.String.Format("{0} = {1}", mi.Name, mi.MemberType));
for(var pi : PropertyInfo in script.GetType().GetProperties())
Debug.Log(System.String.Format("{0} = {1}", pi.Name, pi.GetValue(script, null)));
}
Thanks, Glenno
Hi i this error appears, when i try your script : " The name '$$anonymous$$emberInfo' does not denote a valid type ('not found').Did you mean 'System.Linq.Expressions.$$anonymous$$emberInitExpression'? " What should i do?
Just leave out the type and it works, eg:
for (var mi in script.GetType().Get$$anonymous$$embers())