Search code examples
c#unity-game-enginescriptingmonodevelopmesh

Unity Game Engine Crashing When Trying To Update The Vertex Positions Of A Mesh In Real Time Using A Script


So in unity I’ve created a script which successfully generates a plane mesh made up of triangles. The plane is has 400 vertices (20x20 grid) with 361 squares made up of 2 triangles comprising 3 vertices each (2166 indices). As was mentioned the vertices, indices and normals are set in the start() function with the vertices being loaded into a vector3 array called vertices, the indices being loaded into an array of single floats and the normals being loaded into an array of vector3. These are then assigned to a mesh (representing the plane) int the Start() function like so:

    mesh.vertices = vertices;
    mesh.triangles = triangles;
    mesh.normals = normals;

In the update() function a function is called which calculates new positions for every single vertex in the plane mesh (400):

void Update () 
{
    updateMesh ();
    mesh.vertices = vertices;
}

With the updateMesh function looking like this:

void updateMesh()                                                                       
{                                                                                           
    //This function will update the position of each vertex in the mesh

    for (float i = 0f; i<1f; i=+0.05f) {
        for (float j = 0f; j<1f; j+=0.05f) {
            pos = (int)((i * 20) + (j*20));
            vertices[pos] = updatePt(j, i);

        }
    }
}

Once the new vertices have been updated, the indices and normals remain the same but the newly calculated vertex positions must be loaded onto the mesh object. And this is also attempted in the Update() function as can be seen above.

However as soon as the play button is pressed in unity, the engine crashes and I’m not sure why – is it possible the recalculation function is not finishing its cycle before unity renders? (I have already reduced the number of vertices in the mesh because the same problem was occurring when the mesh had 10000 vertices (100x100 grid)). Or is it because I am not doing something properly in the Update() function?


Solution

  • I think it might be the typo at the line

    for (float i = 0f; i<1f; i=+0.05f) {
    

    It should read += not =+ .

    It is probably getting stuck in an infinite loop because i is never incremented.