Unity Tip: Combine Meshes for Performance and Organization

Robert Prehn
acrossthegalaxy
Published in
2 min readSep 21, 2017

I recently found a little Unity scripting API I wanted to share. Did you know that you can use Mesh.CombineMeshes to take several different meshes, and make them one?

Why would you combine meshes? First, performance. Fewer meshes can mean fewer draw calls, even if the triangle count is the same. You can also reduce your GameObject count. Since each game object comes with some overhead, this can be more efficient. Combining meshes lets you easily and efficiently rotate, scale, translate, and otherwise animate the geometry together. Secondly, combining meshes has the nice advantage of keeping the object hierarchy smaller.

This won’t work in every case. If your objects need to move, translate, scale, or animate independently, combining them is a bad idea. If your objects have different materials, you can still combine them, but you lose a lot of the upside in performance and simplicity.

You can combine meshes in game or editor scripts. For example, your level editor tools could allow your designers to place objects, walls, and floors and move them around independently. You can then bake them together for performance reasons during your build process. You can also combine meshes at runtime. For example, if your procedural level generator builds levels out of prefab chunks, you can still combine those chunks into a single mesh after generation.

So how do you combine meshes in Unity? Here are the steps your script should follow:

  • Make a new mesh to be the target of the combine operation.
  • Make an array of CombineInstance objects with one element per mesh to be combined. These are structs that describes how each mesh should be combined with the others.
  • Call targetMesh.CombineMeshes and pass in the array of CombineInstances.
  • Assign the target mesh to the mesh filter of the combination game object.
  • De-activate or destroy any unneeded game objects (i.e. clean up).

Getting the transform of each CombineInstance right is key. The easiest thing to do, where possible, is use the transform of each game object as the transform of the corresponding CombineInstance. That way, your combined mesh will have all the vertices in the same relative position that the original object did.

Note: The target mesh cannot be one of the meshes that you are combining. You generally want to make a new mesh for this purpose.

The documentation for CombineMesh is here: https://docs.unity3d.com/ScriptReference/Mesh.CombineMeshes.html. This page also links to the docs for CombineInstance. The example in the documentation covers a basic use case. This is where you should start until you are familiar with the options. If you prefer video tutorials, Craig Perko made a video about CombineMesh that you can find here: https://www.youtube.com/watch?v=wYAlky1aZn4.

--

--