Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplify foreach on Transform

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.

Attempt at Balázs' answer

like image 289
Alox Avatar asked Dec 24 '22 20:12

Alox


2 Answers

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();
like image 135
Hans Kesting Avatar answered Dec 28 '22 06:12

Hans Kesting


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.

like image 37
Everts Avatar answered Dec 28 '22 07:12

Everts