Search Unity

Can someone show me how to use C# to copy and modify vertices?

Discussion in 'Scripting' started by Jason210, Feb 24, 2018.

  1. Jason210

    Jason210

    Joined:
    Oct 14, 2012
    Posts:
    131
    I have this code:

    Mesh mesh = GetComponent<MeshFilter>().mesh;
    Vector3[] vertices = mesh.vertices;
    int i = 0;
    while (i < vertices.Length)
    {
    vertices += Vector3.up * Time.deltaTime;
    i++;
    }
    mesh.vertices = vertices;
    mesh.RecalculateBounds();​

    I have some programming knowledge but not much of C#. I need to know how to "connect" this code to a plane of 40 vertices, and just do a very simple morph of it, for example, make each point move upwards by a limited random amount.

    Can someone show me how to do it please?
     
  2. TaleOf4Gamers

    TaleOf4Gamers

    Joined:
    Nov 15, 2013
    Posts:
    825
    Please use code tags:
    https://forum.unity.com/threads/using-code-tags-properly.143875/

    Firstly, thats a weird use of a while loop, a for loop just makes so much sense instead.

    This should be fairly easy if you just break that code down into steps:

    Get the vertices of the mesh:
    Code (CSharp):
    1. Mesh mesh = GetComponent<MeshFilter>().mesh;
    2. Vector3[] vertices = mesh.vertices;
    Loop through all of the vertices and move them up at a rate of 1 Unity unit per second.
    This is where you would change the amount it moves. Probably using Random.Range()
    Code (CSharp):
    1. int i = 0;
    2. while (i < vertices.Length)
    3. {
    4.     vertices += Vector3.up * Time.deltaTime;
    5.     i++;
    6. }
    Re-assign the vertices back to the mesh and recalculate the bounds of the mesh.
    Code (CSharp):
    1. mesh.vertices = vertices;
    2. mesh.RecalculateBounds();
     
    Jason210 likes this.
  3. Jason210

    Jason210

    Joined:
    Oct 14, 2012
    Posts:
    131
    Thanks for explaining the steps.

    I think the reason it shows a while loop is to stop the animation repeating, as a for loop would reset i to zero each frame.