UV unwrap on Runtime optimization
<p>I'm trying to create UVs @ runtime, I'm using a BOX type UVs (similar to BOX UVW in 3ds max) and based my calculation on the face orientation. </p>

<p>I know it's not a good option to create it a runtime but I have no choice :( it's saved after calculation, so I made it once.</p>

<p>BUT I take 40 seconds for a 30000 Vertices... too long</p>

<p>Is there any optimization in my code that can be made?</p>

<p>.</p>

<p>Here is my code feel free to use if you have &lt;5000 vertices Mesh: </p>

<pre><code>public static void CreateUV(ref Mesh mesh)
{

    int i = 0;
    Vector3 p = Vector3.up;
    Vector3 u = Vector3.Cross(p, Vector3.forward);
    if (Vector3.Dot(u, u) &lt; 0.001f)
    {
        u = Vector3.right;
    }
    else
    {
        u = Vector3.Normalize(u);
    }

    Vector3 v = Vector3.Normalize(Vector3.Cross(p, u));

    Vector2[] uvs = new Vector2[mesh.vertices.Length];

    for (i = 0; i &lt; mesh.triangles.Length; i += 3)
    {

        Vector3 a = mesh.vertices[mesh.triangles[i]];
        Vector3 b = mesh.vertices[mesh.triangles[i + 1]];
        Vector3 c = mesh.vertices[mesh.triangles[i + 2]];
        Vector3 side1 = b - a;
        Vector3 side2 = c - a;
        Vector3 N = Vector3.Cross(side1, side2);

        N = new Vector3(Mathf.Abs(N.normalized.x), Mathf.Abs(N.normalized.y), Mathf.Abs(N.normalized.z));



        if (N.x &gt; N.y &amp;&amp; N.x &gt; N.z)
        {
            uvs[mesh.triangles[i]] = new Vector2(mesh.vertices[mesh.triangles[i]].z, mesh.vertices[mesh.triangles[i]].y);
            uvs[mesh.triangles[i + 1]] = new Vector2(mesh.vertices[mesh.triangles[i + 1]].z, mesh.vertices[mesh.triangles[i + 1]].y);
            uvs[mesh.triangles[i + 2]] = new Vector2(mesh.vertices[mesh.triangles[i + 2]].z, mesh.vertices[mesh.triangles[i + 2]].y);
        }
        else if (N.y &gt; N.x &amp;&amp; N.y &gt; N.z)
        {
            uvs[mesh.triangles[i]] = new Vector2(mesh.vertices[mesh.triangles[i]].x, mesh.vertices[mesh.triangles[i]].z);
            uvs[mesh.triangles[i + 1]] = new Vector2(mesh.vertices[mesh.triangles[i + 1]].x, mesh.vertices[mesh.triangles[i + 1]].z);
            uvs[mesh.triangles[i + 2]] = new Vector2(mesh.vertices[mesh.triangles[i + 2]].x, mesh.vertices[mesh.triangles[i + 2]].z);
        }
        else if (N.z &gt; N.x &amp;&amp; N.z &gt; N.y)
        {
            uvs[mesh.triangles[i]] = new Vector2(mesh.vertices[mesh.triangles[i]].x, mesh.vertices[mesh.triangles[i]].y);
            uvs[mesh.triangles[i + 1]] = new Vector2(mesh.vertices[mesh.triangles[i + 1]].x, mesh.vertices[mesh.triangles[i + 1]].y);
            uvs[mesh.triangles[i + 2]] = new Vector2(mesh.vertices[mesh.triangles[i + 2]].x, mesh.vertices[mesh.triangles[i + 2]].y);
        }

    }

    mesh.uv = uvs;
    Debug.Log("Finish");
}
</code></pre>