I ran into a few problems trying to create a Dictionary of Lists in Unity JavaScript. So I thought I’d share some of the tips I learned here.
I’m interested in creating a Dictionary to hold Markov Chain information in order to generate text. So I’d like to be able to create a Dictionary holding a variable length of items for each of its Keys. I’d also like to be able to update the mapping at runtime.
It would look something like this:
- Key1: Item1, Item2, Item3
- Key2: Item4
At runtime, I’d like to be able to say: “Append Item5
to Key2
.”
Here’s what I came up with in Unity JavaScript. I started out by initializing a table
in my script prior to the Start
function. The var table
holds our mapping of Keys of type String
to Values of type List.<int>
, or Lists of integers.
1 2 3 |
|
The first hiccup I ran into is that white space matters when creating Generics in Unity JavaScript. The compiler will throw an error if it sees two >>
in a row.
Then I fill the table with our test mappings.
1 2 3 4 5 |
|
As you can see, you can construct a List from an Array. Cool.
In the Start
function, I iterate over the Keys in the Dictionary, Add the item 4
to the Value of Key c
, and print out the first item of each of the values
. Finally, we check to see whether 4
was appended to the desired entry.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
Then I attach this script to the Main Camera of a fresh Scene for testing purposes. Bada bing, bada boom.
Attaching the script to any old object in the scene would work. I just chose the Main Camera because the camera object is there by default.
This was all relatively straightforward, after I understood some of the quirks of Unity’s JavaScript syntax. You can find an example script using this code here.