Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Help - KeyNotFoundException: The given key was not present in the dictionary ?

Discussion in 'Scripting' started by vetronus, May 26, 2016.

  1. vetronus

    vetronus

    Joined:
    Jan 21, 2016
    Posts:
    11
    Hey guys, I am using this code to take float and fill it in my dictionary

    public void SetFloat(string varID, float value)
    {
    if(floats.ContainsKey(varID))
    {
    floats["varID"] = value;
    }
    else
    {
    floats.Add(varID, value);
    }
    }

    and I am using this code to get back the values from the dictionary

    public void GetFloat(string varID)
    {
    if(floats.ContainsKey(varID))
    {
    return(varID)
    }
    else
    {
    print("It doesn`t contain such ID")
    }
    }


    but I am getting this error every time i call GetFloat("ID") function -

    KeyNotFoundException: The given key was not present in the dictionary.
    System.Collections.Generic.Dictionary`2[System.String,System.Single].get_Item (System.String key) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:150)
    SaveManager.GetFloat (System.String varID) (at Assets/Easy SaveLoad For Begginers/Resources/Scripts/SaveManager.cs:118)
    Sample.Load () (at Assets/Easy SaveLoad For Begginers/Resources/Scripts/Sample.cs:42)
    UnityEngine.Events.InvokableCall.Invoke (System.Object[] args) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:144)
    UnityEngine.Events.InvokableCallList.Invoke (System.Object[] parameters) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:621)
    UnityEngine.Events.UnityEventBase.Invoke (System.Object[] parameters) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:756)
    UnityEngine.Events.UnityEvent.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent_0.cs:53)
    UnityEngine.UI.Button.Press () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:35)
    UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:44)
    UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:52)
    UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerClickHandler] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction`1 functor) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:269)
    UnityEngine.EventSystems.EventSystem:Update()

    Screenshot (55).png
     
  2. traderain

    traderain

    Joined:
    Jul 7, 2014
    Posts:
    108
    change this:
    Code (CSharp):
    1. if(floats.ContainsKey(varID))
    2.     {
    3.         floats["varID"] = value;
    4.     }
    to this:
    Code (CSharp):
    1. if(floats.ContainsKey(varID))
    2.     {
    3.         floats["varID"].Value = value;
    4.     }
     
    vetronus likes this.
  3. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    is that your entire code for "GetFloat(string varID)", because there is no return type, and you're returning the string you're passing in, not the associated float based on the string as the key for the dictionary...


    which line is 118?
     
    vetronus likes this.
  4. SirNiklas

    SirNiklas

    Joined:
    Jun 7, 2015
    Posts:
    85
    Please wrap your source into code-tags.
    This code snippet doesnt make sense:
    Code (CSharp):
    1. public void GetFloat(string varID)
    2. {
    3.    if(floats.ContainsKey(varID))
    4.    {
    5.       return(varID)
    6.    }
    7.    else
    8.    {
    9.       print("It doesn`t contain such ID")
    10.    }
    11. }
    12.  
    Missing semicolons, completely wrong syntax, so I guess this is pseudo-code written by you to let us figure out the problem right?

    You need to use the Dictionary-indexer to lookup the value associated with your varID key.
    And I advise you to use Dictionary.TryGetValue for unsafe value accessing because it is more performance intensive to use Dictionary.ContainsKey.
    Code (CSharp):
    1. public float GetFloat(string varId)
    2. {
    3.    float value = -1;
    4.    if (!floats.TryGetValue(varId, out value))
    5.       Debug.Log("A value stored with the key " + varId + " has not been found.");
    6.  
    7.    return value;
    8. }
    Edit: By the way, have you checked if you really added a new item with "ID" as the key? Maybe this SetFloat("ID") call is not executed because of an if-statement or serialization-errors.
     
    Last edited: May 26, 2016
    vetronus likes this.
  5. SirNiklas

    SirNiklas

    Joined:
    Jun 7, 2015
    Posts:
    85
    This is incorrect. The Dictionary-indexer does not have the returning type KeyValuePair.
     
    vetronus likes this.
  6. traderain

    traderain

    Joined:
    Jul 7, 2014
    Posts:
    108
    Thanks for mentioning that.
    For future reference OP should format his posts like so:
     
    vetronus likes this.
  7. traderain

    traderain

    Joined:
    Jul 7, 2014
    Posts:
    108
    Oh yeah sorry but I don't have proper coding tools with me to test at the moment.
     
    vetronus likes this.
  8. Errorsatz

    Errorsatz

    Joined:
    Aug 8, 2012
    Posts:
    555
    It should be:
    1. floats[varID].Value = value;
    Note passing varID rather than the literal "varID".
     
    vetronus likes this.
  9. vetronus

    vetronus

    Joined:
    Jan 21, 2016
    Posts:
    11
    Hey guys, Finally the problem is resolved :) ! Thanks to all of you !
     
  10. vetronus

    vetronus

    Joined:
    Jan 21, 2016
    Posts:
    11
    Yes, its a pseudo code cause i was not posting it from my formal PC :) I will wrap codes into tags, It was first Post, Please tell me how to do that :)
     
  11. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
  12. SirNiklas

    SirNiklas

    Joined:
    Jun 7, 2015
    Posts:
    85
    What the heck? That literally is what traderain proposed as a solution and we came to the conclusion that this is incorrect. Why repost it again?
     
    traderain likes this.
  13. Errorsatz

    Errorsatz

    Joined:
    Aug 8, 2012
    Posts:
    555
    I was replying to post #2.
    floats["varID"] = value;
    vs
    floats[varID] = value;
     
  14. SirNiklas

    SirNiklas

    Joined:
    Jun 7, 2015
    Posts:
    85
    wari already confessed that his code was not real but pseudo-code. So there is no need to correct syntax errors, and you need to address the quoted user to make it a quote, theres an inbuild feature to do this automatically.
     
  15. Errorsatz

    Errorsatz

    Joined:
    Aug 8, 2012
    Posts:
    555
    I may have cross-posted with that. Also, nobody had mentioned the "varID" thing as opposed to the .Value thing, so I figured I'd mention it. No need to start an inquisition about it. :)

    Not sure what you mean about the quote thing.
     
  16. SirNiklas

    SirNiklas

    Joined:
    Jun 7, 2015
    Posts:
    85
    Quoting somebody means you put in the quoted users name so that everybody knows that its a quote and to who you are referring to. And still, there is no need to correct the syntax error "varID" because it was nonexistant in the real source. This up there is just pseudo code. Written as an example of what the thread-poster had in his script.