0
\$\begingroup\$

I have a list of GameObjects. Half of these GameObjects have Component1, and the other half have Component2. I want to get all of Component1 from the list.

So an example of my list:

var list = new List<GameObject>();
for (int i = 0; i < 10; i++)
{
    list.Add(new GameObject());
}
foreach(var go in list)
{
    if(UnityEngine.Random.Range(0.0f, 1.0f) < 0.5f)
    {
        go.AddComponent<Component1>();
    }
    else
    {
        go.AddComponent<Component2>();
    }
}

I can get all of Component2 by using LINQ as such:

var components1 = list.Where(g => g.GetComponent<Component1>()).Select(r => r.GetComponent<Component1>()).ToList();

But that is very dirty and seems repetitive. Is there a better way to do this?

\$\endgroup\$
1
  • \$\begingroup\$ Using LINQ is probably the easiest / cleanest / shortest way to do it afaik. \$\endgroup\$
    – lvictorino
    Jul 19, 2016 at 21:52

1 Answer 1

1
\$\begingroup\$

LINQ is probably the best way to go, but switch your Select and Where so you don't have to call GetComponent twice

var components1 = list.Select(r => r.GetComponent<Component1>()).Where(g => g!= null).ToList();
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .