- Home /
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?)
Your line of code looks fine and compiles fine for me. The only difference is that I used 'gameObject' rather than 'myGameObject'. How is 'myGameObject' declared and initialized?
Oops, thats a typo. It should be GetComponentsInChildren (which gets all), ins$$anonymous$$d of GetComponentInChildren (this works but it doesn't get all the vertices).
GetComponentsInChildren() returns an array. You will need to get the vertices from each entry in the array in some sort of loop. I don't know if you can process each array entry separately, or you might need to compile all the vertices into a single list. Without context it is hard to suggest specific code.
Answer by robertbu · Apr 30, 2014 at 04:24 AM
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)
.ToArray();
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.
Your answer
Follow this Question
Related Questions
C# Preserving GameObjects' Previous Meshes 1 Answer
Is it possible to make vertices defined by a mesh and mesh filters animating? 0 Answers
How to Change an Object's Mesh to another Object's Mesh via Code C# 1 Answer
MeshCollider is not getting updated when adding vertex to mesh 1 Answer
C# Array of OtherArray's Meshes 1 Answer