Why does my Hashtable try to return an object value?
Hashtable weaponInformation = new Hashtable();
weaponInformation.Add("BulletSpeed", 250);
weaponInformation.Add("GrenadeSpeed", 200);
weaponInformation.Add("MissileSpeed", 125);
This is my current code to set values. The problem I am having is when I try to read my data.
projectilePrefab.GetComponent<Rigidbody2D>().AddForce(turret.transform.up * weaponInformation[(currentWeaponName + "Speed")]);
It is casting the error: Operator '*' cannot be applied to operands of type 'Vector3' and 'object'
When I read the Hashtable values I want it to return an int not an object. If you could, also explain why it would even try to return an object?
Answer by joemane22 · Nov 14, 2015 at 05:38 AM
Because the Hashtable is made to receive any type of object so to get an object of type int back you need to do an implicit conversion
projectilePrefab.GetComponent().AddForce(turret.transform.up * (int)weaponInformation[(currentWeaponName + "Speed")]);
As long as you are sure the object is an integer this will work. Alternatively you could use a Dictionary. It is the same thing as a Hashtable except it only works with one data type. you must add the reference
System.Collections.Generic;
Then declare the dictionary you want like this
//key, value
Dictionary<string, int> weaponInformation = new Dictionary<string, int>();
Then use it as you were using it before without the implicit conversion, this will be much safer in the long run.
Hope this helps!
Your answer
Follow this Question
Related Questions
Dictionary doesn't find value when using new object as key 2 Answers
Null reference on dictionary with Unity's Text Localisation tutorial 0 Answers
[Simple] How to retrieve the Hashtable value, stored in a list? 1 Answer
How can I check for an inputted word against a list of words in a text file? 0 Answers