zero's a life

An extra chance.

Create a Dictionary of Lists in Unity C#

| Comments

Last week, I published an article about creating a Dictionary of Lists in Unity using Unity’s JavaScript. Some of the syntax is changed in C#, but the overall algorithm is exactly the same. I’ve already mentioned the underlying motive, so I’ll dive right in.

Here’s how to create a Dictionary of Lists in C# for Unity.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Dictionary<string, List<int>> table = new Dictionary<string, List<int>>();

void Start() {
    // Fill our table with Lists containing ints using Arrays to intialize
    // the Lists.
    table["a"] = new List<int>(){1};
    table["b"] = new List<int>(){2};
    table["c"] = new List<int>(){3};

    foreach(string str in table.Keys) {
        // Get the value for our Key.
        List<int> value = table[str];

        // If the Key is the desired Key, append to its list.
        if(str == "c") {
            value.Add(4);
        }

        // print the first item in each of the Lists.
        Debug.Log(value[0]);
    }

    // Print the appended item to see that it worked.
    Debug.Log(table["c"][1]);
}

These are the main differences between the Unity JavaScript and C# code. Take a look at the full file in a gist on github.

Comments