Unity中Mesh和subMesh的区别
Unity中的Mesh很好理解,就是一个网格的数据结构,里面记录了顶点、顶点索引等信息:
Mesh mesh = new Mesh();
mesh.vertices = ...
mesh.triangles = ...
mesh.uv = ...//都可以对其赋值
什么是subMesh
Mesh里面有这么一个参数mesh.subMeshCount
,所以说明了subMesh是 属于 Mesh的,subMesh是mesh的子mesh,subMesh所有的顶点数据信息都来自于对应的Mesh,subMesh自身独有的内容,实际上是记录了一串索引的数组,从subMesh取得的索引信息,加上原Mesh具有的顶点信息,我们就可以绘制出原来整个Mesh的一部分,那么subMesh有什么用呢?举个例子,对于一个贴了多种材质(Material)的模型object,往往不同的材质会对应模型不同的部位,当我们将模型导出的时候,如果每一个材质,我们都导出一个完整的模型的mesh,这样无疑是很浪费内存的,所以说,为了进行区分,每一个材质对应的顶点部分对应的mesh,就组成了一个subMesh,即一种材质对应一个subMesh,如果一个模型只有一个材质,那么导出的subMesh自然就只有一个。
可以看看Unity Document的解释:
Each sub-mesh corresponds to a Material in a Renderer, such as MeshRenderer or SkinnedMeshRenderer. A sub-mesh consists of a list of triangles, which refer to a set of vertices. Vertices can be shared between multiple sub-meshes.
Each sub-mesh corresponds to a Material in a Renderer, such as MeshRenderer or SkinnedMeshRenderer. A sub-mesh consists of a list of triangles, which refer to a set of vertices. Vertices can be shared between multiple sub-meshes.
如何创建和读取subMesh
可以利用Mesh.SetTriangles
、Mesh.GetTriangles
等函数来进行读取和存储subMesh的数据,如下图所示。
大致是这么个使用方法,需要设置mesh.subMeshCount:
lineMesh.subMeshCount = 2;
lineMesh.vertices = lineVertices.ToArray();
lineMesh.SetNormals(normals);
//绘制0号submesh
lineMesh.SetIndices(lineIndices[0].ToArray(), MeshTopology.Lines, 0);
Gizmos.DrawMesh(lineMesh, 0, gameObject.transform.position);
//绘制1号submesh
lineMesh.SetIndices(lineIndices[1].ToArray(), MeshTopology.Lines, 1);
Gizmos.DrawMesh(lineMesh, 1, gameObject.transform.position);