- Home /
Var names in Unity javascript
Alright, quick question, is it possible - and if so how - to get a variable name as string? I wanted to make a hash with variable name as key and its value as value without having to type the var name (I swear this makes sense in my application)
Thanks guys!
Answer by Bunny83 · Jul 24, 2011 at 11:12 PM
You already said the magic word "hash". You can use a Hashtable or what even better a generic Dictionary.
A Dictionary allows you to store a value together with a hash-key. You can access the value via the hash value. You can use a string as hashkey, but any other type would do.
import System.Collections.Generic;
var myDict = new Dictionary.<String,int>();
myDict.Add("SomeUniqueName",42);
myDict["SomeUniqueName"] = 55;
Debug.Log(myDict["SomeUniqueName"]);
I'm not sure if the generic syntax works the same way as generic functions in UnityScript. I don't have time to test it but it should work that way.
A HashTable can store any data because it's untyped but it'S also quite slow. If you can you should always use a static-typed-dictionary.
Besides that you can also use Reflection but that's even slower and should be avoided since it can result in very confusing code. It actually breaks the laws of OOP ;)
Answer by PaulBrasfield · Jul 24, 2011 at 10:20 PM
The short answer is that you can't do something like this. That just isn't the way the Java language works.
Your answer
Follow this Question
Related Questions
Comparing two objects properties for the closest 0 Answers
Simple Dictionary / Hashtag system for Inventory with Unityscript only ?? (no C#) 1 Answer
String as variable name, reflection or dictionary or other 2 Answers
Hashtable(or generic dictionary) vs Enum - when do I use which? 1 Answer
Serializing data structures the Unity way. Possible? 1 Answer