Created
November 4, 2024 11:04
-
-
Save taigama/09d4ca966657cfae087cf080e7604184 to your computer and use it in GitHub Desktop.
Improved version of https://gist.github.com/simonwittber/0297a2a8127efddd818d624ce14bd6a8 . With this one, you can extract all sub meshes (inside a Combined Mesh) which be used in a GameObject.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class UnitySubMeshesExtractor | |
{ | |
public static Mesh ExtractSubMesh(Mesh m, int meshIndex, int count, Transform meshRenderHolder) | |
{ | |
Vector3 pos = meshRenderHolder.position; | |
Quaternion rot = meshRenderHolder.rotation; | |
rot.y = -rot.y;// correct the translation calculation | |
var vertices = m.vertices; | |
var normals = m.normals; | |
var uvs = m.uv; | |
var newVerts = new List<Vector3>(); | |
var newNorms = new List<Vector3>(); | |
var newUVs = new List<Vector2>(); | |
int totalTris = 0; | |
var allTris = new List<List<int>>(); | |
for (int iterMesh = 0; iterMesh < count; ++iterMesh) | |
{ | |
var triangles = m.GetTriangles(meshIndex + iterMesh); | |
var newTris = new List<int>(); | |
for (var i = 0; i < triangles.Length; i += 3) | |
{ | |
var A = triangles[i + 0]; | |
var B = triangles[i + 1]; | |
var C = triangles[i + 2]; | |
newVerts.Add(rot * (vertices[A] - pos)); | |
newVerts.Add(rot * (vertices[B] - pos)); | |
newVerts.Add(rot * (vertices[C] - pos)); | |
newNorms.Add(rot * normals[A]); | |
newNorms.Add(rot * normals[B]); | |
newNorms.Add(rot * normals[C]); | |
newUVs.Add(uvs[A]); | |
newUVs.Add(uvs[B]); | |
newUVs.Add(uvs[C]); | |
newTris.Add(totalTris++); | |
newTris.Add(totalTris++); | |
newTris.Add(totalTris++); | |
} | |
allTris.Add(newTris); | |
} | |
var mesh = new Mesh(); | |
mesh.indexFormat = newVerts.Count > 65536 ? IndexFormat.UInt32 : IndexFormat.UInt16; | |
mesh.SetVertices(newVerts); | |
mesh.SetNormals(newNorms); | |
mesh.SetUVs(0, newUVs); | |
mesh.subMeshCount = count; | |
for (int iterMesh = 0; iterMesh < count; ++iterMesh) | |
{ | |
mesh.SetTriangles(allTris[iterMesh], iterMesh, false); | |
} | |
mesh.RecalculateBounds(); | |
mesh.name = m.name + "__" + meshIndex + '_' + count; | |
return mesh; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment