- Home /
Can and should a procedural mesh be shared between multiple GameObjects
I'm creating a mesh for a rounded cube in code (it has 216 vertices, normals etc). And I want to have 100 cubes on screen in my game.
So can (and should) I just run the mesh creation code once to create a mesh and then just assign that mesh to the mesh property of the MeshFilter of each object? Or should I run the createMesh code for each of the 100 cubes, or should I clone the mesh for each object, somehow?
ie
mesh = CreateMesh()
for each object
{
meshFilter.mesh = mesh;
}
OR
for each object:
{
meshFilter.mesh = CreateMesh();
}
Any advice appreciated.
I may want to change the mesh for some objects during the game (eg change the roundness of the cube), so maybe I would then clone the mesh, change it and reassign it for that single GameObject?
Answer by Bunny83 · Nov 05, 2021 at 02:22 AM
If the mesh should be the same, then yes, of course it should be shared. That's also what's happening when you create 100 default cubes in Unity. Each cube will reference the same mesh instance.
However: your code does not share the mesh since you use the mesh property of the MeshFilter. The mesh property will ensure that each instance gets a copy of that mesh. You should use the "sharedMesh" property instead.
Actually using the same mesh would also be a requirement if you want to benefit from GPU instancing.
Thanks for your answer. However, the docs for SharedMesh rather worryingly say: "It is recommended to use this function only for reading mesh data and not for writing". Can you explain that? (https://docs.unity3d.com/ScriptReference/MeshFilter-sharedMesh.html)