- Home /
How to get a List<> from GetComponents?
GetComponents returns a []. Is there any one-liner way to convert that to a Generic (List or whatever)?
Answer by Karwoch · Jun 06, 2019 at 04:20 PM
I always forget this, end up landing here, and loose time to search elsewhere, so I leave this for future myself ;)
List<Collider> collidersToTurnOff = new List<Collider>();
void Awake()
{
GetComponentsInChildren(collidersToTurnOff);
}
Answer by ArkaneX · Feb 02, 2014 at 08:24 PM
With LINQ (requires using System.Linq;
):
var list = GetComponents<SomeComponent>().ToList();
Without LINQ:
var list = new List<SomeComponent>(GetComponents<SomeComponent>());
Code in C#.
Answer by markmmiller · Feb 02, 2014 at 08:21 PM
List<object> list = obj.GetComponents<Thing>().Cast<Object>().ToList();
Should work, otherwise you could write your own function to do it for you.
for(int i = 0; i < arr.Length; ++i)
{
list.Add(arr[i]);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613132349im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Storing return of get components in List 1 Answer
A node in a childnode? 1 Answer
Iterate through Variables in a Script and adding them to a Generic List 1 Answer
Initializing List of generic type via editor - Doesn't work? 1 Answer
null reference exception problem with generic lists in unityscript (i think...) 1 Answer