Get all vertices in gameObject to array.

This seems to work if the gameObject is a mesh itself:

Vector3[] objectVerts = myGameObject.GetComponent<MeshFilter>().mesh.vertices;

However if the mesh is a child of an empty gameObject, it doesnt work since the gameObject itself has no MeshFilter.

So I figured this should work:

Vector3[] objectVerts = myGameObject.GetComponentsInChildren<MeshFilter>().mesh.vertices;

but I get the error
‘System.Array’ does not contain a definition for ‘mesh’ and no extension method ‘mesh’ accepting a first argument of type ‘System.Array’ could be found (are you missing a using directive or an assembly reference?)

GetComponentsInChildren() returns an array, so if you want a single list of all the vertices, the individual vertices need to be combined from each of the mesh filters.

First approach: use a Generic List. Here is a function. You will need to put this at at the top of the file:

 using System.Collections.Generic;

And here the the function:

Vector3[] GetVerticesInChildren(GameObject go) {
	MeshFilter[] mfs = go.GetComponentsInChildren<MeshFilter>();
	List<Vector3> vList = new List<Vector3>();
	foreach (MeshFilter mf in mfs) {
		vList.AddRange (mf.mesh.vertices);
	return vList.ToArray ();

A second approach is to use LinQ. Put this at the top of the file:

 using System.Linq;

Then the follow statement builds the lists:

Vector3[] v = gameObject.GetComponentsInChildren<MeshFilter>()
        .SelectMany(mf => mf.mesh.vertices)

Note for any future people looking at this answer, GetComponentInChildren() returns the components on the parent as well as all the children. For this question it does not matter since the parent is an empty game object.