Search Unity

Question Mesh vertices not being set

Discussion in 'Scripting' started by jedaniels000, May 26, 2020.

  1. jedaniels000

    jedaniels000

    Joined:
    Apr 12, 2020
    Posts:
    6
    I'm having some trouble setting the vertices of a mesh. Below is my code:
    Code (CSharp):
    1. cubeMesh.vertices = new Vector3[12];
    2. for (int vertexIndex = 0; vertexIndex < cubeMesh.vertices.Length; vertexIndex++)
    3.    cubeMesh.vertices[vertexIndex] = vertlist[vertexIndex];
    4.    Debug.Log(vertlist[vertexIndex]);
    5.    Debug.Log(cubeMesh.vertices[vertexIndex]);
    6. }
    When I run the code, the debugger outputs:
    (1.0, 0.0, 0.7)
    (0.0, 0.0, 0.0)
    (0.3, 0.0, 0.3)
    (0.0, 0.0, 0.0)
    ...
    and so on. How could the adjacent lines be different if I'm setting the value of the mesh's vertices to the value contained in the vertex list, and then immediately printing their values to the console? Help would be greatly appreciated.
     
  2. ThermalFusion

    ThermalFusion

    Joined:
    May 1, 2011
    Posts:
    906
    You need to supply Mesh.vertices with a complete array. Mesh.vertices returns a copy of the vertex array and because of this
    Mesh.vertices[x] = y;
    doesn't really do anything. You are just modifying the copy and then throwing it away.
    Create a new array at the start:
    x = new Vector3[y];
    Modify it in loop:
    x = z;
    Then assign it to mesh.
    mesh.vertices = x;
     
    jedaniels000 likes this.
  3. jedaniels000

    jedaniels000

    Joined:
    Apr 12, 2020
    Posts:
    6
    Thank you! This worked.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,689