Search Unity

[SOLVED]Mesh vertex position in world space

Discussion in 'Scripting' started by fozzy, Sep 10, 2009.

  1. fozzy

    fozzy

    Joined:
    Feb 26, 2009
    Posts:
    20
    I need the above, can it be done? Many thanks
     
    supremumstudio likes this.
  2. andeeeee

    andeeeee

    Joined:
    Jul 19, 2005
    Posts:
    8,768
    You can use the Mesh API to get the vertices of your mesh. Converting these local coordinates to world space is very easy - you just need to use Transform.TransformPoint:-
    Code (csharp):
    1. Vector3 worldPt = transform.TransformPoint(meshVert);
     
  3. fozzy

    fozzy

    Joined:
    Feb 26, 2009
    Posts:
    20
    Brilliant thanks!
     
  4. Pixipulp

    Pixipulp

    Joined:
    Feb 10, 2013
    Posts:
    3
    Or you use:
    Code (CSharp):
    1. public Vector3 GetVertexWorldPosition(Vector3 vertex, Transform owner)
    2.     {
    3.         return owner.localToWorldMatrix.MultiplyPoint3x4(vertex);
    4.     }
    which has basically the same result.
     
  5. KeinZantezuken

    KeinZantezuken

    Joined:
    Mar 28, 2017
    Posts:
    53
    Gonna bump this one, I have relevant question. Any idea why this:

    Code (CSharp):
    1. var vertices = GameObject.Find("MuhGO").GetComponent<MeshFilter>.()mesh.vertices;
    2. Vector3 worldPt = transform.TransformPoint(vertices[0]);
    3. GUI.Label(myRect, "World pos: " + worldPt.ToString());
    breaks my mesh renderer? It is simple 2D sprite and I wanna read position of current vertice 0 but for some reason it makes the sprite stuck in a first frame. How can I get the data in "read-only"?
     
  6. villevli

    villevli

    Joined:
    Jan 19, 2016
    Posts:
    89
    You should probably be using a SpriteRenderer instead of MeshRenderer if you have a sprite?

    The problem you have might be caused because you use MeshFilter.mesh which replaces the mesh the filter is using with an instance of that mesh. (this is done only on the first call) You can use sharedMesh if you don't want this.
    Other problem might be that you are transforming the vertex with the wrong transform. You should probably be using the transform of the gameobject "MuhGO".

    I hope you don't have this code in OnGUI or Update as it uses GameObject.Find() which is slow and Mesh.vertices which allocates a new array every time you call it.

    You can use:
    Code (CSharp):
    1. // declare this field in your script
    2. private List<Vector3> vertexBuffer = new List<Vector3>();
    3.  
    4. // call this if the mesh has been modified and you want to get the vertices.
    5. vertexBuffer.Clear();
    6. meshFilter.sharedMesh.GetVertices(vertexBuffer);
     
  7. KeinZantezuken

    KeinZantezuken

    Joined:
    Mar 28, 2017
    Posts:
    53
    villevli

    Thanks, that is probably gonna work, will check later.

    And no, I'm not using Gameobject.Find in Update/onGUI, I fetch them once per scene into dict to quickreference later.