- Home /
Array.map Support
Prewarning: While I did see a similar post referencing C languages... and an answer that drew a line towards Dictionary for .net and Associative array for java-script, I was unable to find an answer.
Essentially I'm looking to add support for the Array.map method on my Unity(JS) script. I'm hoping its as easy as #import magic but, I haven't been able to dig anything up.
This Page Provides a script that would supposedly enable it directly, but alas does not survive the MonoDevelop compile process.
If someone could point me in the correct direction that would be wonderful. Please, be my programming batman!
Answer by Baste · Oct 10, 2014 at 03:57 PM
The problem here is that Unity's JavaScript (UnityScript for clarity) is not JavaScript. In particular, UnityScript uses 'proper' objects, while JavaScript uses prototypes. Thus, the prototype-based 'fix' in your link won't work.
The solution is to just replace the map method with the old-fashioned way; iteration! So where you'd do this in normal JavaScript:
array.map(function(x) {
print(x);
});
you're going to be doing this in UnityScript:
for (var x in array) {
print(value);
}
I know, it's a bummer. In my opinion, you'll want to jump to C# eventually, because the disconnect between JavaScript and UnityScript means that there's pretty much nobody that can help you with your code other than other Unity users, while in C# you have the entire C# community to draw on.
If you're looking for the Map data type, on the other hand, use the Hashtable type. Test it with:
#pragma strict
var foo = new Hashtable();
function Start () {
foo['a'] = 5;
Debug.Log(foo['a']);
}
You should really use Dictionary, not Hashtable. Hashtable is obsolete and has the same issues that the similarly obsolete ArrayList has. By now there's quite a lot of info about Unityscript that can be found pretty easily with searching (mostly here and on the forums), so support isn't really an issue.
Thank you Baste for your helpful information. Could I bother you with a follow up question? I'm interested in learning to write my own methods as I've written my own encoder, xml parser, etc and would like to utilize them in that way rather than calling static functions (for stability reasons). I am planning to learn C# next but after I've found a solid base in UnityScript/derpyJS. Can you recommend some tutorials?
Your answer
![](https://koobas.hobune.stream/wayback/20220613164814im_/https://answers.unity.com/themes/thub/images/avi.jpg)