Memory leak when destroying Terrain

Hi,

I’m working on a project which use a lot of terrains, destroying and instanciating them on the fly. What I found is that materials aren’t destroyed when I call

Destroy(myTerrainObject);

I saw on other topics that materials aren’t automatically destroyed when you destroy a gameobject and that I need to do it manually. But Terrain doesn’t let you access to all the material that it is using.

I linked a unitypackage with this topic which contains a simple scene with the DetectLeaks script and a button which spawn/destroy a terrain. See how the materials count is going up. Resources.UnloadUnusedAsset doesn’t works.

Before I submit a bug report, does anyone know a solution for that or is the problem already known ?

Thanks !

1438463–77075–$TerrainMaterialLeak.unitypackage (934 KB)

I’ve had a similar problem with Destroy() in Unity 4.3 when trying to destroy something I created using Instatiate(). I used DestroyImmediate(gameObject); instead and that works just perfectly.

I replaced Destroy by DestroyImmediate but the material count is still going up.

I can find all materials with Resources.FindObjectsOfTypeAll but after that I don’t know which ones I must destroy. I have multiple instances of terrains, some that need to stay in my scene, other that need to be destroyed so I can’t simply destroy every terrain material that I get with this function…

Bug report is sent !

Still no reply from Unity Tech., and the bug report doesn’t appear on the issue tracker. Did i do something wrong ?

Here is the link to the bug report : http://fogbugz.unity3d.com/default.asp?579048_8ip57o8ialo949bj

Are there somebody that can actually confirm that I’m not the only one to have this problem ?

It’s very frustating because I use a lot of Terrain components, and it keeps crashing after multiple load/unload.

I think we are running into a related issue. I am creating and destroying terrains at runtime but cannot seem to deallocate the terrain data cleanly. Something is still hogging texture-related memory according to the profiler, but it does not seem to be my code (I deallocate texture2Ds loaded at runtime with destroyImmediate when they are not needed and subsequently call Resources.UnloadUnusedAssets).

Any news on this issue…?

I’m currently using Unity 4.5.2 and it seems to be resolved now.

For anyone who stumbles accross this old thread: You need to call these functions to release the TerrainData after destroying the Terrain GameObject by Destroy():

  • Destroy(myTerrainGameObj);
  • Resources.UnloadUnusedAssets();
  • System.GC.Collect();

http://answers.unity.com/answers/940015/view.html

I was creating, modifying and destroying Terrains at runtime and the memory footprint kept increasing. This solved it.