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 ?
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…
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).
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():