Get vertex coordinates from gameobject mesh
Hi guys i would like to get all vertex cordinates of a mesh gameobject . With my script i get always the same coordinates for 24 times (the mesh is a simple box).
Any suggestion ?
Best regards.
void Start ()
{
GameObject gameObject = GameObject.Find("head");
Mesh mesh = gameObject.GetComponent<MeshFilter>().mesh;
Vector3[] vertices = mesh.vertices;
for (var i = 0; i < vertices.Length; i++)
{
direction = transform.TransformPoint(vertices[i]);
Debug.Log(direction);
}
}
Answer by vlee116 · Jul 18, 2021 at 09:52 PM
GameObject myObject = GameObject.Find("head");
Mesh mesh = myObject.GetComponent<MeshFilter>().mesh;
Vector3[] vertices = mesh.vertices;
for (var i = 0; i < vertices.Length; i++)
{
Debug.Log(vertices[i]);
var direction = transform.TransformPoint(vertices[i]);
Debug.Log(direction);
}
You're pretty close @mustang4484, your first problem could be that by using "gameObject" as your object name you could be creating some namespace issues, but I haven't actually tested your code so I'm not sure. Either way, it's good practice to just use a different name for your GameObject. Secondly, you're not properly defining the 'direction' variable. You need to either specify a data type or just use 'var'. Funnily enough I'm doing the exact same thing you are in my current project! I stumbled across your question while doing research
Answer by andrew-lukasik · Jul 17, 2021 at 08:53 PM
Never create variables of type GameObject
with name gameObject
. The same goes for Transform
s names transform
. You will thank yourself later.
Also there is a bug here - your not suppose to transform those vertices by transform
(which is relative to script location and not head transform itself).
This vector is no direction:
direction = transform.TransformPoint(vertices[i]);
but world position of a given vertex:
Vector3 vertexWorldPosition = transform.TransformPoint( vertices[i] );
void Start ()
{
GameObject headGo = GameObject.Find("head");
Transform headTransform = headGo.transform;
Mesh headMesh = headGo.GetComponent<MeshFilter>().sharedMesh;
Vector3[] vertices = mesh.vertices;
var text = new System.Text.StringBuilder();
int numVertices = vertices.Length;
for( int i=0 ; i<numVertices ; i++ )
{
Vector3 vertexWorldPosition = headTransform.TransformPoint( vertices[i] );
text.AppendLine($", ({vertexWorldPosition.x:0.00},{vertexWorldPosition.y:0.00},{vertexWorldPosition.z:0.00})");
}
Debug.Log($"vertices: ( {text} )");
}
Your answer
Follow this Question
Related Questions
Is it possible to make a game object's mesh fit its collider? 1 Answer
How to click and drag a game object along a mesh 0 Answers
vertex Weight Problems 0 Answers
Add collision to mesh 0 Answers