- Home /
Hashtable used as associative array - how to fetch element value?
How do you access a particular element of a Unity hashtable - I assumed it would be similar to accessing an element of an associative array, since the hashtable is a key, value pair. But, I get an error when I try that.
Answer by Bunny83 · Apr 30, 2011 at 01:07 AM
It works like an associative array but with a little difference that the value have to exist before you can access it. To store a value you have to use ContainsKey() to check if it's already in the table, if not use Add() to add a certain key value pair.
I would reccomend to use a Dictionary<> instead of a Hashtable. The generic Dictionary is strongly typed and have much better performance.
A C# example:
Dictionary<string,float> table = new Dictionary<string,float>();
table.Add("Apple",1.25);
To query a value and you're not sure if it exists:
float v = 0.0;
if (table.ContainsKey("Orange"))
v = table["Orange"];
To set a value it's almost the same:
float valueToSet = 5.3;
if (table.ContainsKey("Orange"))
table["Orange"] = valueToSet;
else
table.Add("Orange",valueToSet);
Answer by sneftel · Apr 30, 2011 at 12:56 AM
The Hashtable class is actually part of .Net, not Unity. And yeah, you access elements in much the same way as an array. What's the particular code you were trying to execute, and what is the exact error?
Your answer
![](https://koobas.hobune.stream/wayback/20220613130330im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Optimising dictionary load (in Javascript) 2 Answers
How to store informations 1 Answer
Return a Hashtable. Warning: Implicit downcast from Object to String. 0 Answers
,loop through a hashtable 2 Answers