- Home /
C#, Dynamically accessing properties with a String
Hi there, to make it short, I need to set and get the value of a property of a component using a string. I found this code which is, I believe, supposed to work:
component.GetType().GetProperty("property").GetValue(component, null); component.GetType().GetProperty("property").SetValue(component, "value", null);
But it does not work, it returns absolutely nothing, when I try
Debug.Log(component.GetType().GetProperty("property"));
I did not include "GetValue", because GetProperty returns nothing, an empty line, not even a "null"
I'm one week old in C# so my knowledge is rather limited, Is there something special to do in order for it to work, or any workaround for this?
Thanks.
What is the type of the 'component' variable? You need to have at least a $$anonymous$$onoBehaviour type to get a property from a script you wrote, as far as I know. Because, of course, this particupar script you wrote probably derive from $$anonymous$$onoBehaviour. Also, does it have a property called 'property'?
well, this was an example script, but the specific script looks like this:
public void set($$anonymous$$onoBehaviour component, string[] properties) {
Hashtable hash = new Hashtable(properties.Length); int i = properties.Length; while(i-->0){ Debug.Log(properties[i] + "-" + component.GetType().GetProperty(properties[i]) + "-");//returns nothing hash.Add(properties[i], component.GetType().GetProperty(properties[i]).GetValue(component,null));//Does not work, error because null } resetVals.Add(component, hash); }
all this is in a $$anonymous$$onobehaviour.
oh and when I try to use GetProperties, it returns an array of length 0, so the name of the properties should not be the problem...
I had similar problems when using reflection, I found that looking for fields ins$$anonymous$$d of properties worked. have you tried that?
sweet! This works!! thanks alot! I don't know how this works, should you post this in Answers? Or should I?
Answer by FatWednesday · Sep 21, 2012 at 03:33 PM
I had similar problems when using reflection, I found that looking for fields instead of properties worked. have you tried that?
(reposting comment as answer)
Your answer
![](https://koobas.hobune.stream/wayback/20220613081316im_/https://answers.unity.com/themes/thub/images/avi.jpg)