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

Find GameObcject with specific value inside List

Discussion in 'Scripting' started by wisien92, Sep 10, 2014.

  1. wisien92

    wisien92

    Joined:
    Nov 16, 2012
    Posts:
    56
    Hi i have rather big problem

    Code (CSharp):
    1. public List<GameObject> Cards;
    I have made a list of gameobject. These gameobjects each has attached script called card. Now i have some id and i want to get the card from that list so that gameobject.card.id is the same as id that i have at the beggining.

    Is it doable?
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,377
    I'd use linq.

    Code (csharp):
    1.  
    2. string id = "the id we're searching for";
    3. var go = (from g in Cards
    4.                let c = g.GetComponent<Card>()
    5.                where c != null && c.id == id
    6.                select g);
    7.  
    You need to be sure to include "using System.Linq;" at the top of your script file (C#)
     
    wisien92 likes this.
  3. wisien92

    wisien92

    Joined:
    Nov 16, 2012
    Posts:
    56
    i get 'Cannot find Card ....' in g.GetComponent<Card>()

    but this works
    Code (CSharp):
    1. string g = GameObject.Find("blabla").GetComponent<Card>().id;
     
    Last edited: Sep 10, 2014
  4. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    If you have a list of GameObjects that have Card components then why not just store the list of Card components themselves? Then you could do this alternately
    Code (csharp):
    1.  
    2. Card card = Cards.FirstOrDefault<Card>(c => c.id == myId);
    3. if (card != null)
    4. {
    5.     Debug.Log(card.id);
    6. }
    7.  
     
  5. wisien92

    wisien92

    Joined:
    Nov 16, 2012
    Posts:
    56
    and then i just instantiate gameobject and set it's component to be equal to the selected component?\

    or am i missing something ?
     
  6. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,377
    That means that when you said:

    You were wrong. Because if it cannot find the component, then one isn't on the GameObject, and you don't have a list of gameobjects with 'Card' components on them.
     
  7. wisien92

    wisien92

    Joined:
    Nov 16, 2012
    Posts:
    56
    It was during build of scripts error so it doesn't know what gameobject has attached on that stage (at least i don't think so)