0
foreach (KeyValuePair<String, EngineProperty> kvp in propertyDict)
{
    Debug.Log(kvp.Key.GetType()+" : "+ kvp.Key+ " "+ mainText.text.GetType()+ " "+ mainText.text);
}
slider.value = propertyDict[mainText.text].GetSpeed();

5 items get printed from the foreach loop. The below code is one of them

System.String :   Piston   System.String   Piston

Piston is the key which I'm looking for

But right below the for loop,

when I use this

slider.value = propertyDict[mainText.text].GetSpeed();

I get this error

KeyNotFoundException: The given key was not present in the dictionary.

But key was printed in the for loop. I don't get it.
This is how I initialized

public Dictionary<String, EngineProperty> propertyDict = new Dictionary<String, EngineProperty>();

I have tried replacing everything with String with string, and still, it doesn't work.

What do I do?

MrRobot9
  • 2,402
  • 4
  • 31
  • 68
  • 2
    I suspect the key in the dictionary has a space at the end of it, and `mainText.text` doesn't. You should check that, then work out what you want to do about it. (When printing arbitrary strings, if you put a `'` at the start and end of them, or something similar, it really helps to make any leading or trailing spaces clear.) – Jon Skeet Sep 10 '20 at 17:08
  • 1
    Or just check length of both. – Wiktor Zychla Sep 10 '20 at 17:11
  • Looks like 2 spaces /left/right padding for some reason on the keys. We'd need to see how the KeyValuePairs are constructed. Maybe key it off an enum that represents the set that your currently populating the strings with? – asawyer Sep 10 '20 at 17:14
  • 1
    One may have spaces (database or lookup key). You may need to use Trim() when saving to dictionary or lookup. – jdweng Sep 10 '20 at 17:16

1 Answers1

2

As Jon Skeet said in his comment, the issue looks to be extra spaces. If you look at the first part of the string System.String : Piston, there are 3 spaces between the colon and Piston, but you have only put one in your separator. That means there are 2 spaces at the beginning of Piston. Similarly, there are 3 after Piston, so that means the actual string is Piston . For the mainText, you have a similar 3 spaces before Piston, but none after, according to the string you posted. This would make mainText to be Piston, which doesn't match.

Kyle W
  • 3,702
  • 20
  • 32