The Meshing subsystem extracts meshThe main graphics primitive of Unity. Meshes make up a large part of your 3D worlds. Unity supports triangulated or Quadrangulated polygon meshes. Nurbs, Nurms, Subdiv surfaces must be converted to polygons. More info
See in Glossary data from an external Provider and converts it to a UnityEngine.Mesh. It can also generate an optional UnityEngine.MeshCollider without incurring any main thread stalls.
The main use case for the Meshing subsystem is to surface procedurally-generated meshes, generally from a spatial mappingThe process of mapping real-world surfaces into the virtual world.
See in Glossary algorithm like the one generated from a depth cameraA component which creates an image of a particular viewpoint in your scene. The output is either drawn to the screen or captured as a texture. More info
See in Glossary. There is no limit on the size of the mesh, or the frequency of updates.
Mesh generation occurs asynchronously on a background thread, so extracting data from an external provider doesn’t block the main thread to, for example, bake the mesh colliderAn invisible shape that is used to handle physical collisions for an object. A collider doesn’t need to be exactly the same shape as the object’s mesh - a rough approximation is often more efficient and indistinguishable in gameplay. More info
See in Glossary.
The Meshing subsystem has two basic queries:
C# users can get the mesh infos from the XRMeshSubsystem
instance method:
public bool TryGetMeshInfos(List<MeshInfo> meshInfosOut);
This maps directly to the C call to UnityXRMeshProvider::GetMeshInfos
and is typically called once per frame to obtain the current list of tracked meshes.
The following C implementation can use the provided allocator
object to allocate an array of UnityXRMeshInfo
s which it should then fill out:
UnitySubsystemErrorCode(UNITY_INTERFACE_API * GetMeshInfos)(
UnitySubsystemHandle handle, void* pluginData, UnityXRMeshInfoAllocator * allocator);
The allocated memory is owned by Unity (typically using a stack allocator, so allocations are very fast):
typedef struct UnityXRMeshInfo
{
UnityXRMeshId meshId;
bool updated;
int priorityHint;
} UnityXRMeshInfo;
If nothing has changed since the last call to TryGetMeshInfos, you can return false to avoid filling out the array each frame.
Field | Description |
---|---|
meshId | A 128-bit unique identifier. The Provider generates these values, which can be a pointer to mesh data, but you need to be able to generate a specific mesh by its ID. |
updated | The only state Unity needs is whether the mesh has been updated since the last time it was generated. Determining whether the mesh was added or removed is done automatically; reporting the existence of a mesh that Unity doesn’t know about is surfaced as Added, while not reporting a mesh that was previously reported marks the mesh as Removed. |
priorityHint | C# interprets this value, but you might want to, for example, provide a C# component that prioritizes which mesh to generate based on it. Unity doesn’t use this value. |
In C#, TryGetMeshInfos populates a List<MeshInfo>
, which includes the mesh state:
public enum MeshChangeState
{
Added,
Updated,
Removed,
Unchanged
}
Based on the mesh change state and the priority hint value, a C# component can then decide which mesh(es) to generate next.
From C#, you can generate a specific mesh asynchronously using the XRMeshSubsystem instance method:
public extern void GenerateMeshAsync(
MeshId meshId,
Mesh mesh,
MeshCollider meshCollider,
MeshVertexAttributes attributes,
Action<MeshGenerationResult> onMeshGenerationComplete);
This enqueues a mesh for generation. You can enqueue as many meshes as you need, but you might want to limit the number of meshes that are concurrently generated to a few at a time.
Unity always calls the provided onMeshGenerationComplete
delegate, even if an error occurs.
Meshes are generated in two phases, following an acquire and release model:
UnitySubsystemErrorCode(UNITY_INTERFACE_API * AcquireMesh)(
UnitySubsystemHandle handle,
void* pluginData,
const UnityXRMeshId * meshId,
UnityXRMeshDataAllocator * allocator);
AcquireMesh
is called on a background thread, so you can do as much processing in this method as you like, including computationally-intensive work such as generating the mesh itself. This function can return immediately or span several frames.
If you provide a MeshCollider
to GenerateMeshAsync
, Unity also computes the MeshCollider’s acceleration structure (“Bake Physics” in the above diagram). This can be time-consuming for large meshes, so it also occurs on the worker thread.
Finally, when the data is ready, Unity writes it to the UnityEngine.Mesh
and/or UnityEngine.MeshCollider
on the main thread. Afterwards, Unity calls ReleaseMesh
, also on the main thread:
UnitySubsystemErrorCode(UNITY_INTERFACE_API * ReleaseMesh)(
UnitySubsystemHandle handle,
void* pluginData,
const UnityXRMeshId * meshId,
const UnityXRMeshDescriptor * mesh,
void* userData);
BecauseReleaseMesh
is called on the main thread, it should return quickly. Typically, this is used to free resources allocated during AcquireMesh
.
AcquireMesh
offers two means of providing mesh data to Unity: Unity-managed and provider-managed.
To let Unity manage the memory, use:
UnityXRMeshDescriptor* (UNITY_INTERFACE_API * MeshDataAllocator_AllocateMesh)(
UnityXRMeshDataAllocator * allocator,
size_t vertexCount,
size_t indexCount,
UnityXRIndexFormat indexFormat,
UnityXRMeshVertexAttributeFlags attributes,
UnityXRMeshTopology topology);
This returns a struct with pointers to buffers based on an intersection of these attributes
and the vertex attributes requested from C#. The provider should then copy the appropriate data to the buffers.
When you use this paradigm, you don’t have to free the memory, because Unity will recycle the memory after the call to ReleaseMesh
.
Instead of letting Unity manage the memory, you can point it at your own data. The data must remain valid until ReleaseMesh
is called.
Use MeshDataAllocator_SetMesh
to provide your own UnityXRMeshDescriptor
whose non-null pointers point to valid data:
void(UNITY_INTERFACE_API * MeshDataAllocator_SetMesh)(
UnityXRMeshDataAllocator * allocator, const UnityXRMeshDescriptor * meshDescriptor);
Your AcquireMesh
implementation can call:
void(UNITY_INTERFACE_API * MeshDataAllocator_SetUserData)(
UnityXRMeshDataAllocator * allocator, void* userData);
Unity passes the userData
pointer back to your ReleaseMesh
implementation. This is particularly useful when you’re using provider-managed memory.
void Update()
{
if (s_MeshSubsystem.TryGetMeshInfos(s_MeshInfos))
{
foreach (var meshInfo in s_MeshInfos)
{
switch (meshInfo.ChangeState)
{
case MeshChangeState.Added:
case MeshChangeState.Updated:
AddToQueueIfNecessary(meshInfo);
break;
case MeshChangeState.Removed:
RaiseMeshRemoved(meshInfo.MeshId);
// Remove from processing queue
m_MeshesNeedingGeneration.Remove(meshInfo.MeshId);
// Destroy the GameObject
GameObject meshGameObject;
if (meshIdToGameObjectMap.TryGetValue(meshInfo.MeshId, out meshGameObject))
{
Destroy(meshGameObject);
meshIdToGameObjectMap.Remove(meshInfo.MeshId);
}
break;
default:
break;
}
}
}
// ...
while (m_MeshesBeingGenerated.Count < meshQueueSize && m_MeshesNeedingGeneration.Count > 0)
{
// Get the next mesh to generate. Could be based on the mesh's
// priorityHint, whether it is new vs updated, etc.
var meshId = GetNextMeshToGenerate();
// Gather the necessary Unity objects for the generation request
var meshGameObject = GetOrCreateGameObjectForMesh(meshId);
var meshCollider = meshGameObject.GetComponent<MeshCollider>();
var mesh = meshGameObject.GetComponent<MeshFilter>().mesh;
var meshAttributes = shouldComputeNormals ? MeshVertexAttributes.Normals : MeshVertexAttributes.None;
// Request generation
s_MeshSubsystem.GenerateMeshAsync(meshId, mesh, meshCollider, meshAttributes, OnMeshGenerated);
// Update internal state
m_MeshesBeingGenerated.Add(meshId, m_MeshesNeedingGeneration[meshId]);
m_MeshesNeedingGeneration.Remove(meshId);
}
}
void OnMeshGenerated(MeshGenerationResult result)
{
if (result.Status != MeshGenerationStatus.Success)
{
// Handle error, regenerate, etc.
}
m_MeshesBeingGenerated.Remove(result.MeshId);
}
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.
When you visit any website, it may store or retrieve information on your browser, mostly in the form of cookies. This information might be about you, your preferences or your device and is mostly used to make the site work as you expect it to. The information does not usually directly identify you, but it can give you a more personalized web experience. Because we respect your right to privacy, you can choose not to allow some types of cookies. Click on the different category headings to find out more and change our default settings. However, blocking some types of cookies may impact your experience of the site and the services we are able to offer.
More information
These cookies enable the website to provide enhanced functionality and personalisation. They may be set by us or by third party providers whose services we have added to our pages. If you do not allow these cookies then some or all of these services may not function properly.
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us to know which pages are the most and least popular and see how visitors move around the site. All information these cookies collect is aggregated and therefore anonymous. If you do not allow these cookies we will not know when you have visited our site, and will not be able to monitor its performance.
These cookies may be set through our site by our advertising partners. They may be used by those companies to build a profile of your interests and show you relevant adverts on other sites. They do not store directly personal information, but are based on uniquely identifying your browser and internet device. If you do not allow these cookies, you will experience less targeted advertising. Some 3rd party video providers do not allow video views without targeting cookies. If you are experiencing difficulty viewing a video, you will need to set your cookie preferences for targeting to yes if you wish to view videos from these providers. Unity does not control this.
These cookies are necessary for the website to function and cannot be switched off in our systems. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms. You can set your browser to block or alert you about these cookies, but some parts of the site will not then work. These cookies do not store any personally identifiable information.