[Optimization] Mesh vertice finding

Hello,

I have a mesh and what I have to do is to find the farest vertice for each axis. So it will give me 6 points:
the higher on x, the higher on y, the higher on z, the lower on x, the lower on y and the lower on z.

I made this loop to do that script:

for(int i = 0; i < mesh.vertices.Length; i++)
        {
            if(mesh.vertices[i].x > pointRight.x)
                pointRight = mesh.vertices[i];

            else if (mesh.vertices[i].x < pointLeft.x)
                pointLeft = mesh.vertices[i];

            if (mesh.vertices[i].y > pointUp.y)
                pointUp = mesh.vertices[i];

            else if (mesh.vertices[i].y < pointDown.y)
                pointDown = mesh.vertices[i];

            if (mesh.vertices[i].z > pointFar.z)
                pointForward = mesh.vertices[i];

            else if (mesh.vertices[i].z < pointNear.z)
                pointBackward = mesh.vertices[i];
        }

But I have to do that on big meshes (70k+ vertices) and it takes lot of time.
I tried to use multithreading but I’m doing this loop in Start function so it causes problems.

So there is a way to optimize that loop ? or maybe reduice vertices number in unity ?

Thanks for answers.

You can also use Mesh.bounds to get the bounding box, that looks pretty similar to what you’re doing already?

1 Like

yes it’s pretty much like what I want to do but can I get, for example, the position of the max vertice on the Y axis ? or X axis ? or Z axis?

Not really, you only get the bound edges - not particular vertex positions. The only way to get that is to do what you’ve already been doing. Why don’t you just make your code output the vertices in a JSON file that you can load in later? That way you only have to precalculate them once.

I managed to do what I wanted with mesh.bounds.

Thanks for the help.