Procedurally generated mesh randomly appearing invisible

I have a 10x10 grid of cubes, each cube can be either enabled (visible) or disabled (invisible). To avoid both the overhead of instantiating new GameObjects as well as the black lines that sometimes appear between the blocks, I have written a script that combines the cube meshes into a single mesh every time the mesh is changed.

The problem is, the resulting mesh is visible only when it is formed from a full 10x10 grid of blocks. 9x10 or anything smaller will appear invisible. The strange part being, I use the exact same combined mesh for the object’s collider, and it works fine. Changing the material or shader has no effect. The inspector will show the wireframe of the mesh at runtime when I look at the generated mesh of a full 10x10 grid, but if it’s a 9x10 grid, the wireframe preview is no longer visible.

I don’t think the problem is with my mesh combining script, because the collider works as expected, and if I use Mesh.CombineMeshes with the merge submeshes option turned off, the mesh also renders correctly. However, I specifically want to merge the submeshes.

I’ve tried to figure out a reason for this behaviour for days now and looked up every possible answer here, but have found nothing. Is this a bug?


Also, when I was previously working on this on a (rather ancient) laptop, I noticed the number of batched draw calls going up whenever I was looking at an area with the invisible meshes (when they were small enough to dynamically batch). I tried disabling dynamic batching from the project, and that fixed it on the laptop. However, on my main desktop machine the dynamic batching setting has no effect on the invisibility problem. This kind of so far seemingly random behaviour initially lead me to consider a bug in Unity.

Use Mesh.RecalculateBounds.

Well, I think I solved it.

I had cached the mesh of the block (there is going to be different types) in an array, and when combining the meshes it would look up the current mesh for each block. Initially I had set the mesh of a cleared block as null, but in a previous iteration of the system there was some problem with that and I had replaced null with simply an empty new Mesh. That had worked, and as said, the colliders formed nicely. I was experimenting with every possible detail, and decided to try and change the system so that the cached mesh array would use null instead of an empty mesh, and the code would specifically skip trying to add meshes set to null. Now the rendering works as well!

I don’t understand why though, as there’s no difference that I can notice in the arrays of the meshes before and after applying this. And I still have no idea why dynamic batching or different computers would affect this, but I assume it’s a hardware/driver thing and how they deal with textures and meshes. Won’t be able to test this on the laptop for a while though, but let’s hope this solution is solid :slight_smile: