Friday, August 7, 2015

Unity Tutorial - how to make a Dictionary show up in the editor

I discovered how awesome Dictionaries are this week (yes I haven't been coding in Unity C# that long ok hehe). It's basically a key-value pair fancy array thing :)

Here's how you'd use it:

Dictionary<string, string> nameOfMyDictionary = new Dictionary<string, string> ();

(Remember to include the System.Collections.Generic; namespace at the top of your file, otherwise this won't work...)

Then, you can add stuff to it with code using the Add() function, etc. Similar to Lists.

Anyway, I discovered that they don't show up the Editor like normal arrays do. And that made me a little sad. So, here's a small workaround I discovered. I'm sure it's not the best way to do it, but it works for me.

Firstly, create a struct containing the key-value pair variables, and remember to add System.Serializable to allow them to show up in the editor:

[System.Serializable]
public struct NameOfStruct
{
public string  string1UniqueKey;
public string string1Value;
}

Next, declare an Array of your new Struct, like so:

public NameOfStruct[] myDictionaryStruct;

This makes the array show up in the Unity Editor, where you can edit it:


So, fill in a few values:


We're almost done. Now we simply need to assign these values to our Dictionary. We do that in the Start() function with a simple for loop:

void Start () 
{
for (int i = 0; i < myDictionaryStruct.Length; i++)
{
nameOfMyDictionary.Add (myDictionaryStruct[i].string1UniqueKey, myDictionaryStruct[i].string1Value);
}
}

It works great, now you can use the dictionary as you normally would. For example, let's say I want to get the value of Alpha, I would simply type in:

nameOfMyDictionary["Alpha"]

That would then be equal to "One" - pretty cool hey?

Here's a screenshot of my code:



(click to make it bigger)


Hope this little trick helps you in some way!

No comments:

Post a Comment