How does one find a variable by name?

I’m writing a small scripting language for the game I’m working on, and it would make my job substantially easier if there’s a way to access a variable by its name as a string.

Sample line from one of my scripts:

player health +50

I want Unity to execute the following:

player.SendMessage(“varchange”, [“health”, “+50”])

The function varchange would then add 50 to the ‘health’ variable of player.

Is there a way to write the ‘varchange’ function so I can send it any variable name (health, magic, position, etc.) and not have an enormous switch statement somewhere?

Yes, but that seems like a horrible way of handling things. You’re using SendMessage - which is inherently slow, and then you’ll either have to use reflection or some kind of hash-table or dictionary to lookup your variables (by reference if you store them in a hash table) both of which are relatively slow operations. To do that for something as basic as setting a variable seems like making your life very hard for little or no real gain.

Your design also doesn’t seem to offer any control over where the variable might be. What happens if several different behaviours have a variable of the same name?

I can’t think that this is the best solution to your problem. Can you describe what you’re trying to achieve instead of the method you’re trying to use?

It’s a bit advanced, but you could use reflection. Though honestly, this sounds more like you should just create multiple methods or structure this is a more efficient way.

C# Reflection (I believe the API is duplicated in JavaScript)