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

[Answered] Find <CustomComponent> by CustomComponent.name in a List<CustomComponent>

Discussion in 'Scripting' started by abelreyes, Oct 29, 2015.

  1. abelreyes

    abelreyes

    Joined:
    Sep 11, 2013
    Posts:
    28
    Good afternoon,
    I'm working on an extension for unity, and I need a fast (performance) method for obtaining a Component from a known Component.name.

    In that case, I have a Component called Key that has a public string name inside. I save all my Key's on List<Key> keys, and I need to recover one of that keys by key.name...

    My actual code uses a second List<string> that, after List<Key> values are assigned, goes through each List<Key> value getting it's name and assigning it to List<string>. Then I've created a function that performs a binary search over the second list saving item founded index into a variable and using it to get the key that has same index (List<Key>[index]).

    Is there any faster method? I need to call this on Update, so it must be as fast as posible...

    Thanks everyone!
     
  2. roojerry

    roojerry

    Joined:
    Mar 18, 2013
    Posts:
    68
  3. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,744
    Never before has a one-word answer so completely and accurately answered a question....
     
    abelreyes likes this.
  4. abelreyes

    abelreyes

    Joined:
    Sep 11, 2013
    Posts:
    28
    Woo, thanks you! I've heard about Dictionary, but didn't imagine that was the utility... Thank tou a lot!
     
  5. ensiferum888

    ensiferum888

    Joined:
    May 11, 2013
    Posts:
    317
    Ever since I discovered Dictionaries I use them everywhere I need fast lookups 1:1 relationships are awesome that way.

    Sometimes I'll even use:
    Code (CSharp):
    1. Dictionary<string, List<GameObject>> master;