RenderMeshSystemV2 has substantial amount of memory leak

Simple code of creating 1000 quad meshes:

using Unity.Entities;
using Unity.Mathematics;
using Unity.Rendering;
using Unity.Transforms;
using UnityEngine;

public class TestSystem : ComponentSystem
{
    Material mat = new Material(Shader.Find("Standard"));

    protected override void OnCreate()
    {
        for (int i = 0; i < 1000; i++)
        {
            Mesh mesh = new Mesh();
            mesh.vertices = new Vector3[] { new Vector3(1, 1, 0), new Vector3(1, -1, 0), new Vector3(-1, -1, 0), new Vector3(-1, 1, 0) };
            mesh.normals = new Vector3[] { new Vector3(0, 0, -1), new Vector3(0, 0, -1), new Vector3(0, 0, -1), new Vector3(0, 0, -1) };
            mesh.triangles = new int[] { 0, 1, 2, 2, 3, 0 };
            var entity = EntityManager.CreateEntity(typeof(LocalToWorld), typeof(Translation));
            EntityManager.SetComponentData(entity, new Translation { Value = new float3(i * 2, 0, 0) });

            var renderMesh = new RenderMesh();
            renderMesh.mesh = mesh;
            renderMesh.material = mat;
            EntityManager.AddSharedComponentData(entity, renderMesh);
        }
    }

    protected override void OnUpdate()
    {

    }
}
  • Unity 2019.1.1f1 (Windows 10)
  • Entities 0.0.12-preview.31
  • Hybrid Renderer 0.0.1-preview.11

Enter playmode with the above TestSystem, and watch memory usage go up constantly (roughly 12MB per second on my end and proportional to the amount of meshes you are drawing). These memory won’t get freed up after exiting playmode either.

In one of my projects where I’m drawing thousands of unique meshes using RenderMesh, the Editor pretty much crashes after a couple minutes in Playmode. On the other hand, doing the same mesh generation with traditional MeshFilter and MeshRenderer does not leak memory.

You are creating meshes and materials without cleaning them up.
Creating one mesh for each quad seems like a poor idea. Can you share them? It will make things run much faster, since batching can take advantage of it. Also i’d recommend using a material in the project folder instead of creating it from code.

Hi @Joachim_Ante_1 thanks for the reply. The quad meshes are created only 1000 times (at one time, not every update). The Editor go up in memory usage forever (until crash). And unfortunately, I cannot use batching because my game generates procedural meshes at runtime (should still be a common scenario right?). The code above is the minimal reproducible version of generating 1000 unique meshes and makes the memory leak observable. The same code in monobehaviour (without using ECS & Hybrid Renderer) does not leak memory:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestScript : MonoBehaviour
{

    void Start()
    {
        for (int i = 0; i < 1000; i++)
        {
            Mesh mesh = new Mesh();
            mesh.vertices = new Vector3[] { new Vector3(1, 1, 0), new Vector3(1, -1, 0), new Vector3(-1, -1, 0), new Vector3(-1, 1, 0) };
            mesh.normals = new Vector3[] { new Vector3(0, 0, -1), new Vector3(0, 0, -1), new Vector3(0, 0, -1), new Vector3(0, 0, -1) };
            mesh.triangles = new int[] { 0, 1, 2, 2, 3, 0 };
            var go = new GameObject();
            go.transform.Translate(i * 2, 0, 0);
            go.AddComponent<MeshFilter>().mesh = mesh;
            go.AddComponent<MeshRenderer>().material = new Material(Shader.Find("Standard"));
        }
    }

}

Have you run it through the profiler? It should be very obvious if there’s anything within ecs code that’s allocating so much ram. Is the number of entities exploding?

I tested your code and don’t get runaway consumption. I’m using the same packages but am still on 2019.1.0f2. Did it only start happening after upgrading?

  • Edit -
    Sorry, I stand corrected. Was looking at the profiler which shows nothing but I also bleed around 8mb/sec.

Thanks for testing on your end. So you are also seeing the memory leak that just keeps going up indefinitely and never gets freed right?

Yeah profiler is not too obvious in this case, though you can still observe the total memory allocation going up. It’s easier to observe in Task Manager where the memory number just goes up and up until unity crashes.

Yes, by my calc it’s roughly 210 bytes per mesh per frame. Not sure if it’s exponential but after a bit it was increasing by 16mb a second.

I rolled back to Entities .27 and Renderer .7 and checked against 2019.2 and it still occurs. I presume it’s unmanaged allocations due to not showing up in profiler?
It only happens in Editor so perhaps it’s somewhere in the safety checks that’s allocating and not disposing.

Yes, possibly. If so, then it must be some hardcoded safety checks or something not straightforward to turn off as I already tried turning off the obvious ones (with no luck).

For work, I’m doing some ECS + Procedural mesh generation. And it cannot meaningfully continue until this issue is fixed. Right now I have to restart the Editor every 10 to 20 minutes to avoid the crash.

I’m surprised this hasn’t been spotted before as it’s a significant leak. Even with only 100 meshes I still get about 3-4mb per/sec. Perhaps it doesn’t affect everyone though.

Having butchered my way through the RenderMeshSystemV2, I’m just guessing that it’s maybe caused within the BatchRenderGroup.AddBatch method which I think is part of the core Unity so no source code?
I found line 666 (auspicious :)) of InstancedRenderMeshBatchGroup.cs is the last point at which you won’t get mem leaks and the AddBatch on this line causes allocations.
I can’t say for sure whether it’s AddBatch or a flow on effect cos the code in there is heavier than I can be bothered wading through. Maybe file a bug report as it’s possibly only something Unity can solve anyway.

Yeah I did pretty much the same today, going through RenderMeshSystemV2, but got stuck on BatchRendererGroup. It’s a blackbox right now, can’t find too much info on it.

I filed a bug at the same time I started this thread. But hopefully we can escalate this here and potentially find a workaround in the meanwhile.

Even the Standalone Player may have some problems with RenderMesh. Because another thing I noticed is that the CPU and Memory utilization of rendering 1000 static quad meshes is considerably higher using RenderMesh than using traditional Monobehaviour.

2 Likes

This is because it requires a chunk per entity (16k * 1000) and all the overhead that entails, especially in Editor with safety checks.
This particular scenario is a mile deep and an inch wide from ecs perspective so doesn’t gain much benefit other than getting rid of GameObject.

Well said! The overhead definitely and greatly exceeded my expectations. I probably need to go back to the drawing board with ECS + Procedural Mesh Terrain (which was really what I was testing).

Good news is the bug was just confirmed and replicated on Unity’s side.

1 Like

That’s great. Another bug down. I get nowhere near the spammed error messages I used to these days. It’s all getting more stable finally.

1 Like

Has anyone found a workaround? I can’t continue my game development because of this memory leak=(

Can confirm the memory leak from code in OP is still present in the latest versions (entities 0.1.1-preview, unity 2019.3.0b4). Maybe we should escalate this? I too simply cannot work with the Hybrid Renderer because of this.

Escalate? Beyond Joachim? Where? ROFL

BTW, you’re using a preview package in a beta Unity version, so please, be patient. If you cannot afford waiting around for fixes and stuff, do not use beta or preview features, stick to the tech/LTS versions and final packages.

I’m asking for some attention for a confirmed editor crashing bug from 5 months ago that hasn’t been addressed, and including the issue tracker url so people can upvote it if this is an issue for them. And, that’s what I mean by escalate. If you always go to Joachim to escalate a bug, then good for you.

And oh please, this has nothing to do with the package in preview or Unity version. If a package responsible for rendering makes the editor crash after rendering some simple quads, I don’t care if it’s in preview, I’ll make sure the dev knows, and if it haven’t been addressed in 5 months, I’ll mention to them again.

I see you didn’t read the thread.

Oh which thread?

This thread. Joachim was the first who answered on this thread, which means he (was) aware what’s happening. That’s why I asked you if you want to escalate it beyond him. https://discussions.unity.com/t/742064/2

Yeah I know… I started this thread. I don’t know if Joachim was actually aware of what’s happening. He had some wrong assumptions in his reply.