Is it possible to simplify the following code by using Linq?
Transform parent;
List<GameObject> children = new List<GameObject>();
foreach (Transform child in parent)
{
children.Add(child.gameObject);
}
I was hoping to simply write parent.ForEach() but transforms don't have such convenience. Does anyone know of a simplification for this?
This is only curiosity and not necessary.
EDIT: parent is not a list of children but a transform.
If Transform
implements IEnumerable
, but not IEnumerable<Transform>
then you first need to convert it to the generic version before you can use Linq:
List<GameObject> children = parent
.Cast<Transform>()
.Select(t => t.gameObject)
.ToList();
Your case is not going to work out as you expect using Linq. One thing you can do is use an extension method as shown bellow.
public static class Extension{
public static IEnumerable<Transform> GetChildren(this Transform tr)
{
List<Transform> children = new List<Transform>();
foreach (Transform child in tr)
{
children.Add(child);
}
// You can make the return type an array or a list or else.
return children as IEnumerable<Transform>;
}
}
and you use it as:
IEnumerable<Transform> trs = parent.GetChildren();
EDIT: the magic happens on the this keyword in the parameter. The method gets called by the instance but is actually static. The calling instance gets added to the parameter list. Without getting too deep, it makes a static method available on an instance. You do not need any addition on your own code if you do not place in a specific namespace.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With