Working with Hashtables in Unity

A Hashtable is a collection of key-value pairs that allows you to store and retrieve data efficiently. Each key in a Hashtable must be unique, and it is used to access the corresponding value. In Unity, Hashtables are part of the System.Collections namespace and can be particularly useful for storing non-generic data structures.

Creating a Hashtable

To use a Hashtable in Unity, you first need to import the System.Collections namespace and then initialize a new Hashtable object. Here’s an example:

using System.Collections;
using UnityEngine;

public class HashtableExample : MonoBehaviour
{
    void Start()
    {
        Hashtable myHashtable = new Hashtable();

        // Adding key-value pairs
        myHashtable.Add("PlayerName", "Alex");
        myHashtable.Add("Score", 1500);
        myHashtable.Add("Level", 5);

        // Accessing values
        Debug.Log("Player Name: " + myHashtable["PlayerName"]);
        Debug.Log("Score: " + myHashtable["Score"]);
        Debug.Log("Level: " + myHashtable["Level"]);
    }
}

Adding and Accessing Data

You can add data to a Hashtable using the Add method. To retrieve a value, use the key inside square brackets:

myHashtable.Add("Health", 100);
int health = (int)myHashtable["Health"];
Debug.Log("Health: " + health);

If a key already exists, attempting to use Add will throw an exception. Instead, use the key directly to update the value:

myHashtable["Health"] = 80; // Updates the value associated with the key

Checking for Keys and Values

To check if a key exists in the Hashtable, use the ContainsKey method. Similarly, use ContainsValue to check for a value:

if (myHashtable.ContainsKey("Score"))
{
    Debug.Log("Score exists: " + myHashtable["Score"]);
}

if (myHashtable.ContainsValue(1500))
{
    Debug.Log("Value 1500 is in the Hashtable.");
}

Removing Data

You can remove an entry from the Hashtable using the Remove method:

myHashtable.Remove("Level");
Debug.Log("Level removed.");

Iterating Through a Hashtable

To iterate through all key-value pairs in a Hashtable, use a foreach loop:

foreach (DictionaryEntry entry in myHashtable)
{
    Debug.Log("Key: " + entry.Key + ", Value: " + entry.Value);
}

Limitations of Hashtables

Hashtables are non-generic and lack type safety. If you need better type safety and performance, consider using the generic Dictionary from the System.Collections.Generic namespace. Hashtables are mainly useful when working with non-generic collections or interfacing with older codebases.

Conclusion

Hashtables in Unity provide a straightforward way to manage key-value pairs in your projects. While they are not the most modern collection type, they remain a valid choice for many scenarios. By understanding how to create, access, and manipulate Hashtables, you can manage data efficiently in your Unity applications.

Links
Unity 6