b3agz / Code-A-Game-Like-Minecraft-In-Unity

Project files for a Youtube tutorial series on coding a game like Minecraft in Unity.
298 stars 237 forks source link

Mesh Memory Leak #23

Open KowsarAtz opened 2 years ago

KowsarAtz commented 2 years ago

In chunk.cs CreateMesh, before assigning the new mesh to meshFIlter (meshFilter.mesh = mesh;), we have to destroy the old mesh (Object.Destroy(meshFilter.sharedMesh);); otherwise we will face memory leak. The leak is disastrous especially when you put lots of blocks in game (>1000).

TeriyakiGod commented 2 years ago

Can you explain why? Why do we have to destroy the shared mesh and why does it cause a leak?

KowsarAtz commented 2 years ago

Can you explain why? Why do we have to destroy the shared mesh and why does it cause a leak?

Sorry if I'm answering late. Unused mesh or material will not be collected by the garbage collector, So when you are replacing the old mesh with the new one, you have to destroy the old one yourself. In order to access the old mesh, you have to use meshFilter.sharedMesh instead of meshFilter.mesh because the latter will give a new instance of the mesh and you don't want that.

I suggest reading the following links as well: