DrawMeshInstanced in Editor/SceneView

Hi,

I am trying to do a custom foliage rendering system in version 2018.3.0f2 and uses DrawMeshInstanced to draw the meshes. It is working without problems when in play mode, but I would like to draw them in the scene view as well to have a visual feedback when painting.

The problem is that in editor, the call to DrawMeshInstanced seems to be kept in memory and keeps being added to when calling it again, making the editor very slow very fast.

The batches keeps increasing until the computer just crash.
I tried to call the render method in different callback but the result is always the same.
So if anyone has any idea how to make that work, I would be very thankful.
The render code:

            Mesh mesh = trees[treeInfo.treeIndex].mesh;
            for (int i = 0; i < trees[treeInfo.treeIndex].materials.Count; i++)
            {
                Material mat = trees[treeInfo.treeIndex].materials[i];
                int batch = treeInfo.positions.Count / 1024;
                for (int j = 0; j <= batch; j++)
                {
                    int count = Mathf.Min(1023, treeInfo.positions.Count - j * 1024);
                    Graphics.DrawMeshInstanced(mesh, i, mat, treeInfo.positions.GetRange(j * 1024, count));
                }
            }

I tried calling it in Update, OnPreCull, OnSceneGUI. All had the same problem.

Ok so I finally managed to make it work correctly.
To make it work correctly, I just put the render call in the update function, made the script execute in edit mode, and when a change occurs on the structure of the object, calls EditorUtility.SetDirty(target). The SetDirty seems to also update the render in some way.

Result:

[ExecuteInEditMode]
public class Terrain{
   ...
   private void Update(){
      Render();
   }
}
public void Paint(){
   // update the structure
   ...
   EditorUtility.SetDirty(target);
}

#edit:
I think I understand the reason for the leak, it seems DrawMeshInstanced does this only when not specifying a camera as parameter. When specifying the camera, everything works right even when using Camera.onPreCull callback.

4 Likes

Good job! I just met this problem one hour ago and didn’t find a way to fix it. Your solution really works for me. Thanks a lot!

Same thing happens to me, I noticed it when rendering transparent objects, all DrawMeshInstanced calls stack up until it’s no longer transparent anymore

Thanks marking the scene dirty fixed the problem for me

Not sure why, but I wasn’t having this problem 'til unity 6. This solution works great, thanks man.