Question by
SAE-MID · Oct 20, 2021 at 09:11 AM ·
textureuv mapping
Problem with automatic generated UV
Hello, i created a sscript, that generates a UV-Map for a mesh with no UVs. But the problem is like in the picture, any of the math or rotation is wrong and i dont find the answer. Can anybody fix my code to help me please. The script can be placed direct on the gameobject.
Here is the .blend file https://drive.google.com/file/d/1F1FE_FT-P4VmJP8IzB8lUNMwXSVdI7yU/view?usp=sharing
private void CreateUVTest()
{
Transform root = transform; //gameObject.transform.GetChild(0);
{
Transform[] transforms = root.GetComponentsInChildren<Transform>();
//CombineInstance[] combine = new CombineInstance[transforms.Length];
for (int i = 0; i < transforms.Length; i++)
{
//calc uv
MeshFilter mf = transforms[i].GetComponent<MeshFilter>();
var triangles = mf.mesh.triangles;
mf.mesh.RecalculateNormals();
mf.mesh.RecalculateBounds();
mf.mesh.RecalculateTangents();
var verts = mf.mesh.vertices;
if (mf != null)
{
Vector2[] uvs = new Vector2[verts.Length];
for (int index = 0; index < triangles.Length; index += 3)
{
// Get the three vertices bounding this triangle.
Vector3 v1 = verts[triangles[index]];
Vector3 v2 = verts[triangles[index + 1]];
Vector3 v3 = verts[triangles[index + 2]];
// Compute a vector perpendicular to the face.
Vector3 normal = Vector3.Cross(v3 - v1, v2 - v1).normalized;
//Plane plane = new Plane(v1, v2, v3);
//Vector3 normal = Vector3.right;
// Form a rotation that points the z+ axis in this perpendicular direction.
// Multiplying by the inverse will flatten the triangle into an xy plane.
Quaternion rotation = Quaternion.Inverse(Quaternion.LookRotation(normal));
//v1 = transform.TransformDirection(rotation * v1);
//v2 = transform.TransformDirection(rotation * v2);
//v3 = transform.TransformDirection(rotation * v3);
v1 = rotation * v1;
v2 = rotation * v2;
v3 = rotation * v3;
// Assign the uvs, applying a scale factor to control the texture tiling.
int scale = 1;
uvs[triangles[index]] = (Vector2)(v1) * scale;
uvs[triangles[index + 1]] = (Vector2)(v2) * scale;
uvs[triangles[index + 2]] = (Vector2)(v3) * scale;
}
mf.sharedMesh.uv = uvs;
}
}
}
}
texture.png
(397.3 kB)
Comment
Your answer
Follow this Question
Related Questions
UV distortions in Blender when connecting vertices. 0 Answers
Can I add the same UV coordinates to multiple vertices? 0 Answers
Imported FBX Issue. Textured Material turn into 1 coloured blur. 0 Answers
instantiate gameobject with the uv 0 Answers
What causes UV-mapping inconsistencies between projects? 2 Answers