Dictionary: User-Choice Data

To explore a simple example of using a C# Dictionary to store user choices, imagine that a player can choose one of 3 different options that correspond to unlocking or locking some options within another scene or game situation. Since we're creating a simple prototype, we can provide the options as buttons within a panel that opens after some dialog has completed that gives back-story of the choice and options.

GameData.cs: Create a C# Dictionary

The first choice when creating a dictionary is to determine the dataType of the key, value elements that it will hold. A very flexible option is to use string for the key and the value, so that's what we'll use in this example. Keep in mind, dictionaries are very flexible, the dataType of the value can be an entire dictionary. Imagine a string-type key of "food" where the associated value being an entire dictionary of different food types and quantities, where the whole dictionary is stored in a scriptableObject, so it could be exported/ imported into any project. Dictionaries are very useful data-structures for storing game-type information. First, we'll add a Dictionary< string, string> to GameData, then we add a method to add or update a key-value pair and a method to access the value that is stored with a key. See info on the page linked below on for additional details about C# Dictionaries.

pageDictionary

GameData.cs Version 2

 private Dictionary<string,string> choiceData = new Dictionary< string,string>();
   
   
 public void SaveChoice( string choiceKey, string choiceValue)
    {

        if (choiceData.ContainsKey(choiceKey))
        {
            choiceData[choiceKey] = choiceValue; //change stored value
            Debug.Log("Choice Changed" + choiceKey + " : " + choiceValue);
        }
        else
        {
            choiceData.Add(choiceKey, choiceValue); //adds key,value pair
            Debug.Log("Choice Data Created" + choiceKey + " : " + choiceValue);
        }
    }

    public string GetChoice( string choiceKey)
    {
        string choiceValue = "None";
        choiceData.TryGetValue(choiceKey, out choiceValue);
        Debug.Log("Choice Data Accessed" + choiceKey + " : " + choiceValue);
        return choiceValue;
    }

Last updated