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. Dismiss Notice

Just an FYI

Discussion in 'Scripting' started by kelvinwop, Feb 12, 2017.

  1. kelvinwop

    kelvinwop

    Joined:
    Dec 15, 2014
    Posts:
    36
    Apparently, when:

    Figure 1:
    Code (CSharp):
    1. try
    2. {
    3.     return somedictionary["some key that doesn't exist"];
    4. }
    5. catch(System.Exception e)
    6. {
    7.     Debug.Log("bad stuff happened: " + e.ToString());
    8.     //do something else
    9.     return -1;
    10. }
    and you get some dictionary value not found... and decide to stop the game (you're playing in unity), unity just gets obscenely slow and unresponsive.


    I changed it to:

    Figure 2:
    Code (CSharp):
    1. if (somedictionary.ContainsKey("some key that doesn't exist"))
    2.     return somedictionary["some key that doesn't exist"];
    3. else
    4.     return -1;
    5.  
    And the problem went away after hitting the stop button, so I assume the code in Figure 1 causes some bad stuff in unity. I'm writing this because I didn't save for a little bit... and unity died.

    Now you all know. Always check your dictionary keys before using them :/
    And rethrow exceptions. I dunno if that's the problem... it might be.
     
  2. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    Just use TryGetValue.
    It returns true when something was found and you get the result via the 'out ...' parameter. Otherwise it return false and you can do alternative stuff.
     
  3. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,398
    Except that doesn't happen here, so I suspect you have something else going on.

    --Eric
     
  4. kelvinwop

    kelvinwop

    Joined:
    Dec 15, 2014
    Posts:
    36
    Oh, it's just me? I'll have to do additional tests later then.