mesh.vertices position not correct

I wanted to use vertices on meshes to create specific and accurate visual effects but am unable as I got stuck. It seems that I can’t get the correct or exact position of a mesh’s vertices. Am I not using this function correctly?

This is the code (C#) I am using:

public Transform target;
private Mesh mesh;
private Vector3[] vertices = new Vector3[0];

void Update()
{
    mesh = target.GetComponent<MeshFilter>().mesh;
    print(target.GetComponent<MeshFilter>().mesh.vertices[0]);
    Debug.DrawLine(transform.position, mesh.vertices[0]);
}

I have my target (A cube) sitting at 0,0,5. It’s first vertice I am attempting to debug should be sitting at 0.5,-0.5,5.5.

From the print (it says 0.5, -0.5, 0.5) and the drawline debug goes there too. It seems it is at the origin point 0,0,0 rather than where the object is actually at.

I have also tried this, which is the same script but on the cube object pointing from it’s vertice to the camera, and the same result.

void Update()
{
    print(GetComponent<MeshFilter>().mesh.vertices[0]);
    Debug.DrawLine(GetComponent<MeshFilter>().mesh.vertices[0], Camera.mainCamera.transform.position);
}

Any help is much appreciated, whether I have to use another solution or fix this one, I don’t mind.

Vertex position are in local space, as in the vertex positions of the mesh do not update or change as you move an object around in the world, only the object’s main transform is updated. If the game engine updated the vertex position of every single mesh every frame we’d never be able to have millions of polygons moving around in real time.

In order to get the world space position of a vertex instead of the local/object space position, simply add the object’s transform.position to the vertex position.

Mesh mesh = target.GetComponent<MeshFilter>().mesh;
Debug.DrawLine(Camera.mainCamera.transform.position, transform.position + mesh.vertex[0]);

Presumably your cube has a transform attached to it which you are using to translate the cube in the Z direction. You are getting the raw vertex positions, and will want to transform them by the same matrix attached to the cube. Use Transform.TransformPoint:

http://unity3d.com/support/documentation/ScriptReference/Transform.TransformPoint.html