- Home /
Changing Y Value in Vertex Array?
I was working from a tutorial on procedural mesh generation, and I decided to try something out. I wanted to go through the array of points that I had created and make their Y values all 1. However, the program didn't really seem to do anything. Here's the program:
public class ProceduralMesh : MonoBehaviour {
Mesh mesh;
Vector3[] vertices;
int[] triangles;
void Awake () {
mesh = GetComponent<MeshFilter>().mesh;
}
// Use this for initialization
void Start () {
MakeMeshData();
CreateMesh();
for (int i = 0; i < vertices.Length; i++)
{
vertices[i].y = 1;
}
}
// Update is called once per frame
void MakeMeshData () {
//Create array of verts
vertices = new Vector3[] {new Vector3 (0, 0, 0), new Vector3 (0, 0, 1), new Vector3 (1, 0, 0), new Vector3 (1, 0, 1)};
//Create array of ints
triangles = new int[] {0, 1, 2, 2, 1, 3};
}
void CreateMesh () {
mesh.Clear();
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.RecalculateNormals();
}
}
The for loop is what I was using to make it go through the list. Basically, the mesh just stayed at y = 0. It's probably something super simple, but all help would be gratefully received:)
Answer by Tobychappell · May 30, 2018 at 01:12 AM
On the mesh object you wish to Edit, you want to call SetVertices and pass the collection of vertices.
https://docs.unity3d.com/ScriptReference/Mesh.SetVertices.html
After doing so you would need to tell the mesh to recalculate it's normals
https://docs.unity3d.com/ScriptReference/Mesh.RecalculateNormals.html
If you're going to be updating the mesh a lot, you'd be able to increase/save performance by calling the MarkDynamic method on the mesh object.
https://docs.unity3d.com/ScriptReference/Mesh.MarkDynamic.html
I'm not 100% sure on this, but in your code the array of verts is the same array of vests in the mesh object. When you're setting y to be 1, that mesh is seeing that change, however this data hasn't been sent to the GPU, it would be bad to update the mesh vertex data every time a single vert was changed as that would consume allot more of the bandwidth between cpu and gpu. Hence $$anonymous$$arkDynamic, not really sure what that does under the hood, but I guess it optimises the way it'll communicate with the GPU for this mesh. Again I'm not a graphics engineer, this is more of a gut feeling of WHY your mesh wasn't updating.
OH SIC$$anonymous$$!! Thank you so much! Do you know how exactly to use that SetVertices? I can't quite figure it out...
mesh.SetVertices(vertices);
mesh.RecalculateNormals();
Or a quicker fix, you can simply call 'Create$$anonymous$$esh()' after you set the vertices y.
WOW HAHA I cannot believe that I didn't think of calling Create$$anonymous$$esh() after setting the vertices! Thank you so much!!