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!

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 :wink:

The short answer is that you can’t do something like this. That just isn’t the way the Java language works.