Find GameObcject with specific value inside List

Hi i have rather big problem

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?

I’d use linq.

string id = "the id we're searching for";
var go = (from g in Cards
               let c = g.GetComponent<Card>()
               where c != null && c.id == id
               select g);

You need to be sure to include ā€œusing System.Linq;ā€ at the top of your script file (C#)

1 Like

i get ā€˜Cannot find Card …’ in g.GetComponent()

but this works

string g = GameObject.Find("blabla").GetComponent<Card>().id;

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

Card card = Cards.FirstOrDefault<Card>(c => c.id == myId);
if (card != null)
{
    Debug.Log(card.id);
}

and then i just instantiate gameobject and set it’s component to be equal to the selected component?\

or am i missing something ?

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.

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)