What would be the fastest way, if we are talking about system performance here, of reading string as a variable name. So far I’ve read that there are options like reflection, dictionary or using an array. So I’m kinda confused right now, what are the differences between them and what method should i be using.
And just so for the idea, what i would like to achieve:
public string a="box";
public int box = 10;
So usual way of accessing variable box would be
But instead, how would i go if I wanted to achieve this type of method of accessing the variable box(syntax is wrong here of course, It’s just for the idea)
something.a; //And it would read it as something.box;
You can do this using reflection, but it will be significantly slower than resolving the property at compile-time. I agree with @iwaldrop that there is almost certainly a better way to do whatever it is you’re trying to do.
But to answer your question, assuming
instance in the name of your class instance and
myProperty is the name of public property whose value you want, just do
You could defiantly use a dictionary. Why you’d want to, however, is a question you should really consider.
public class DictionaryMethods : MonoBehaviour
private Dictionary <string, Action> methods;
methods = new Dictionary <string, Action>();