Documentation

Unity Engine


User Manual

Script Reference

Unity Engine


Mesh

A class that allows you to create or modify meshes.
Read time 12 minutesLast updated 3 days ago

Definition

  • Type: Class
  • Namespace: UnityEngine
  • Assembly: UnityEngine.CoreModule
  • Inherits from: Object
public sealed class Mesh : Object

Remarks

Meshes contain vertices and multiple triangle arrays.
Conceptually, all vertex data is stored in separate arrays of the same size. For example, if you have a mesh of 100 Vertices, and want to have a position, normal and two texture coordinates for each vertex, then the mesh should have Mesh.vertices, Mesh.normals, Mesh.uv and Mesh.uv2 arrays, each being 100 in size. Data for i-th vertex is at index "i" in each array.
For every vertex there can be a vertex position, normal, tangent, color and up to 8 texture coordinates. Texture coordinates most often are 2D data (Vector2), but it is possible to make them Vector3 or Vector4 if needed. This is most often used for holding arbitrary data in mesh vertices, for special effects used in shaders. For skinned meshes, the vertex data can also contain Mesh.boneWeights.
The mesh face data, i.e. the triangles it is made of, is simply three vertex indices for each triangle. For example, if the mesh has 10 triangles, then the Mesh.triangles array should be 30 numbers, with each number indicating which vertex to use. The first three elements in the triangles array are the indices for the vertices that make up that triangle; the second three elements make up another triangle and so on.
Note that while triangle meshes are the most common use case, Unity also supports other mesh topology types, for example Line or Point meshes. For line meshes, each line is composed of two vertex indices and so on. See Mesh.SetIndices and MeshTopology.
Simple vs Advanced Mesh API
The Mesh class has two sets of methods for assigning data to a Mesh from script. The "simple" set of methods provide a basis for setting the indices, triangle, normals, tangents, etc. These methods include validation checks, for example to ensure that you are not passing in data that would include out-of-bounds indices. They represent the standard way to assign Mesh data from script in Unity.
There is also an "advanced" set of methods, which allow you to directly write to the mesh data with control over whether any checks or validation should be performed. These methods are intended for advanced use cases which require maximum performance. They are faster, but allow you to skip the checks on the data you supply. If you use these methods you must make sure that you are not supplying invalid data, because Unity will not check for you.
The "advanced" methods are: Mesh.SetVertexBufferParams, Mesh.SetVertexBufferData, Mesh.SetIndexBufferParams, Mesh.SetIndexBufferData, Mesh.SetSubMesh, and you can use the MeshUpdateFlags to control which checks or validation are performed or omitted. Use Mesh.AcquireReadOnlyMeshData to take a read-only snapshot of Mesh data that you can use with C# Jobs and Burst, and Mesh.AllocateWritableMeshData with Mesh.ApplyAndDisposeWritableMeshData to create Meshes from C# Jobs and Burst.
Manipulating meshes from a script
There are three common tasks that might want to use the Mesh API for:
1. Building a mesh from scratch: should always be done in the following order:
a) Assign Mesh.vertices
b) Assign Mesh.triangles.
using UnityEngine;public class Example : MonoBehaviour{ Vector3[] newVertices; Vector2[] newUV; int[] newTriangles; void Start() { Mesh mesh = new Mesh(); GetComponent<MeshFilter>().mesh = mesh; mesh.vertices = newVertices; mesh.uv = newUV; mesh.triangles = newTriangles; }}
2. Modifying vertex attributes every frame:
a) Get vertices
b) Modify them
c) Assign them back to the mesh.
using UnityEngine;public class Example : MonoBehaviour{ void Update() { Mesh mesh = GetComponent<MeshFilter>().mesh; Vector3[] vertices = mesh.vertices; Vector3[] normals = mesh.normals; for (var i = 0; i < vertices.Length; i++) { vertices[i] += normals[i] * Mathf.Sin(Time.time); } mesh.vertices = vertices; }}
3. Continously changing the mesh triangles and vertices:
a) Call Mesh.Clear to start fresh
b) Assign vertices and other attributes
c) Assign triangle indices.
It is important to call Mesh.Clear before assigning new vertices or triangles. Unity always checks the supplied triangle indices whether they don't reference out of bounds vertices. Calling Mesh.Clear then assigning vertices then triangles makes sure you never have out of bounds data.
using UnityEngine;public class ExampleClass : MonoBehaviour{ Vector3[] newVertices; Vector2[] newUV; int[] newTriangles; void Start() { Mesh mesh = GetComponent<MeshFilter>().mesh; mesh.Clear(); // Do some calculations... mesh.vertices = newVertices; mesh.uv = newUV; mesh.triangles = newTriangles; }}

Constructors

Constructor

Description

Mesh()Creates an empty Mesh.

Properties

Property

Description

bindposeCountThe number of bind poses in the Mesh.
bindposesThe bind poses. The bind pose at each index refers to the bone with the same index.
blendShapeCountReturns BlendShape count on this mesh.
boneWeightsThe BoneWeight for each vertex in the Mesh, which represents 4 bones per vertex.
boundsThe bounding volume of the Mesh.
colorsVertex colors of the Mesh.
colors32Vertex colors of the Mesh.
indexBufferTargetThe intended target usage of the Mesh GPU index buffer.
indexFormatFormat of the mesh index buffer data.
isReadableReturns true if the Mesh is read/write enabled, or false if it is not.
normalsThe normals of the Mesh.
skinWeightBufferLayoutThe dimension of data in the bone weight buffer.
subMeshCountThe number of sub-meshes inside the Mesh object.
tangentsThe tangents of the Mesh.
trianglesAn array containing all triangles in the Mesh.
uvThe texture coordinates (UVs) in the first channel.
uv2The texture coordinates (UVs) in the second channel.
uv3The texture coordinates (UVs) in the third channel.
uv4The texture coordinates (UVs) in the fourth channel.
uv5The texture coordinates (UVs) in the fifth channel.
uv6The texture coordinates (UVs) in the sixth channel.
uv7The texture coordinates (UVs) in the seventh channel.
uv8The texture coordinates (UVs) in the eighth channel.
vertexAttributeCountReturns the number of vertex attributes that the mesh has. (Read Only)
vertexBufferCountGets the number of vertex buffers present in the Mesh. (Read Only)
vertexBufferTargetThe intended target usage of the Mesh GPU vertex buffer.
vertexCountReturns the number of vertices in the Mesh (Read Only).
verticesReturns a copy of the vertex positions or assigns a new vertex positions array.

Methods

Method

Description

AddBlendShapeFrameAdds a new blend shape frame.
ClearClears all vertex data and all triangle indices.
ClearBlendShapesClears all blend shapes from Mesh.
CombineMeshesCombines several Meshes into this Mesh.
GetAllBoneWeightsGets the bone weights for the Mesh.
GetBaseVertexGets the base vertex index of the given /sub-mesh/.
GetBindposesGets the bind poses of the Mesh.
GetBlendShapeBufferRetrieves a GraphicsBuffer that provides direct read and write access to GPU blend shape vertex data.
GetBlendShapeBufferRangeGet the location of blend shape vertex data for a given blend shape.
GetBlendShapeFrameCountReturns the frame count for a blend shape.
GetBlendShapeFrameVerticesRetreives deltaVertices, deltaNormals and deltaTangents of a blend shape frame.
GetBlendShapeFrameWeightReturns the weight of a blend shape frame.
GetBlendShapeIndexReturns index of BlendShape by given name.
GetBlendShapeNameReturns name of BlendShape by given index.
GetBonesPerVertexThe number of non-zero bone weights for each vertex.
GetBoneWeightBufferRetrieves a GraphicsBuffer that provides direct read and write access to GPU bone weight data.
GetBoneWeightsGets the bone weights for the Mesh.
GetColorsGets the vertex colors of the Mesh.
GetIndexBufferRetrieves a GraphicsBuffer to the GPU index buffer.
GetIndexCountGets the index count of the given /sub-mesh/.
GetIndexStartGets the starting index location within the Mesh's index buffer, for the given /sub-mesh/.
GetIndicesUse this method overload if you control the life cycle of the list passed in and you want to avoid allocating a new array with every access.
GetNativeIndexBufferPtrRetrieves a native (underlying graphics API) pointer to the index buffer.
GetNativeVertexBufferPtrRetrieves a native (underlying graphics API) pointer to the vertex buffer.
GetNormalsGets the vertex normals of the Mesh.
GetSubMeshGet information about a sub-mesh of the Mesh.
GetTangentsGets the tangents of the Mesh.
GetTopologyGets the topology of a sub-mesh.
GetTrianglesFetches the triangle list for the specified sub-mesh on this object.
GetUVDistributionMetricThe UV distribution metric can be used to calculate the desired mipmap level based on the position of the camera.
GetUVsGets the texture coordinates (UVs) stored in a given channel.
GetVertexAttributeReturns information about a vertex attribute based on its index.
GetVertexAttributeDimensionGet dimension of a specific vertex data attribute on this Mesh.
GetVertexAttributeFormatGet format of a specific vertex data attribute on this Mesh.
GetVertexAttributeOffsetGet offset within a vertex buffer stream of a specific vertex data attribute on this Mesh.
GetVertexAttributesGet information about vertex attributes of a Mesh.
GetVertexAttributeStreamGets the vertex buffer stream index of a specific vertex data attribute on this Mesh.
GetVertexBufferRetrieves a GraphicsBuffer that provides direct acces to the GPU vertex buffer.
GetVertexBufferStrideGet vertex buffer stream stride in bytes.
GetVerticesGets the vertex positions of the Mesh.
HasVertexAttributeChecks if a specific vertex data attribute exists on this Mesh.
MarkDynamicOptimize mesh for frequent updates.
MarkModifiedNotify Renderer components of mesh geometry change.
OptimizeOptimizes the Mesh data to improve rendering performance.
OptimizeIndexBuffersOptimizes the geometry of the Mesh to improve rendering performance.
OptimizeReorderVertexBufferOptimizes the vertices of the Mesh to improve rendering performance.
RecalculateBoundsRecalculate the bounding volume of the Mesh and all of its sub-meshes with the vertex data.
RecalculateNormalsRecalculates the normals of the Mesh from the triangles and vertices.
RecalculateTangentsRecalculates the tangents of the Mesh from the normals and texture coordinates.
RecalculateUVDistributionMetricRecalculates the UV distribution metric of the Mesh from the vertices and uv coordinates.
RecalculateUVDistributionMetricsRecalculates the UV distribution metrics of the Mesh from the vertices and uv coordinates.
SetBindposesSets the bind poses of the Mesh.
SetBoneWeightsSets the bone weights for the Mesh.
SetColorsSet the per-vertex colors of the Mesh.
SetIndexBufferDataSets the data of the index buffer of the Mesh.
SetIndexBufferParamsSets the index buffer size and format.
SetIndicesSets the index buffer of a sub-mesh, using a part of the input array.
SetNormalsSet the normals of the Mesh.
SetSubMeshSets the information about a sub-mesh of the Mesh.
SetSubMeshesSets information defining all sub-meshes in this Mesh, replacing any existing sub-meshes.
SetTangentsSet the tangents of the Mesh.
SetTrianglesSets the triangle list for the sub-mesh.
SetUVsSets the texture coordinates (UVs) stored in a given channel.
SetVertexBufferDataSets the data of the vertex buffer of the Mesh.
SetVertexBufferParamsSets the vertex buffer size and layout.
SetVerticesAssigns a new vertex positions array.
UploadMeshDataUpload previously done Mesh modifications to the graphics API.

Static Methods

Method

Description

AcquireReadOnlyMeshDataGets a snapshot of Mesh data for read-only access.
AllocateWritableMeshDataAllocates data structures for Mesh creation using C# Jobs.
ApplyAndDisposeWritableMeshDataApplies data defined in MeshData structs to Mesh objects.

Structs

Struct

Description

Mesh.MeshDataA struct containing Mesh data for C# Job System access.
Mesh.MeshDataArrayAn array of Mesh data snapshots for C# Job System access.

Inheritance

Inherited Members

Operators

Operator

Description

operator ==Compares two object references to see if they refer to the same object.
boolDetermines whether the object exists.
operator !=Compares if two objects refer to a different object.