- Home /
How to merge per triangle UVs
I am trying to generate correct UVs for meshes I have combined with CombineMeshes().
UnityEditor.Unwrapping.GeneratePerTriangleUV() seems to do what I want, but the documentation just says "You'll need to merge them yourself." This function seems to be giving me back one UV pair per triangle, but I don't know how to merge/map those onto the vertex UV pairs that the mesh seems to have (the UV array is the same size as the vertex array, while the generated UV array is the same size as the triangle array).
Here is my function:
public GameObject MeshCombination(Material material, CombineInstance[] combines)
{
GameObject newMeshObj = new GameObject(material.name);
MeshFilter targetFilter = null;
targetFilter = newMeshObj.AddComponent<MeshFilter>();
newMeshObj.AddComponent<MeshRenderer>();
targetFilter.sharedMesh = new Mesh();
targetFilter.sharedMesh.CombineMeshes(combines);
Vector2[] triangleUV = UnityEditor.Unwrapping.GeneratePerTriangleUV(targetFilter.sharedMesh);
// How do I merge the per triangle UVs and assign them to the mesh?
targetFilter.renderer.material = material;
return newMeshObj;
}
Thanks in advance for whatever help you guys can give me!
Answer by virgilcwyile · Mar 05, 2018 at 08:38 AM
I have a code which works for me. However I cannot use that in my project as UnityEditor code cannot be used in the Builds. Below is the code:
private static Vector2[] GenerateUvs(Mesh mesh)
{
Vector2[] uvs = new Vector2[mesh.vertices.Length];
Vector2[] all = UnityEditor.Unwrapping.GeneratePerTriangleUV(mesh);
int[] triangles = mesh.triangles;
int count = 0;
while (count < uvs.Length)
{
for (int i = 0; i < triangles.Length; i++)
{
if (triangles[i] == count)
{
uvs[count] = all[i];
count++;
}
}
}
return uvs;
// return null;
}
Uhm, you just turned an O(n) operation into an O(n²). If you look closely at the body of your inner loop you may notice that this:
if (triangles[i] == count)
{
uvs[count] = all[i];
count++;
}
actually results in this:
uvs[triangles[i]] = all[i];
Therefore you only need a single loop that looks like this:
for (int i = 0; i < triangles.Length; i++)
{
uvs[triangles[i]] = all[i];
}
However keep in $$anonymous$$d that the method might generate seperate UVs for two adjacent triangles. If the mesh is a shared mesh the result would be wrong as you would assign two different UVs to the same vertex so only the last assigned value would take effect. The result would be wrong in this case. In that case you would have to split the vertex which is quite a bit more complicated. However if you created the vertices the way you need them it should work just fine.
Your answer
Follow this Question
Related Questions
2 Textures on a single mesh 1 Answer
3D Procedural Hex UV Map 0 Answers
can't put texture materials on imported mesh. 1 Answer