I’m writing a game in Unity with programmatically created simple GameObjects (colored cubes), which each have their own Material and Mesh and may also have child GameObjects. I have found that I have memory leaks for Mesh and Material whenever a cube is removed. So I have developed the method below which does fix the problem.
But is this sensible? What do other people do? And are there any other GameObject Components I should worry about that may also cause leaks.
private static void DestroyGameObject(GameObject gameObject)
{
int numberOfChildren = gameObject.transform.childCount;
for (int index = 0; index < numberOfChildren; index++)
{
GameObject child = gameObject.transform.GetChild(index).gameObject;
CubeWallView.DestroyGameObject(child); // Recursive
}
//
Renderer renderer = gameObject.GetComponent<Renderer>();
if (renderer != null)
{
Material[] materials = renderer.sharedMaterials;
if (materials != null)
{
foreach (Material material in materials)
{
UnityEngine.Object.Destroy(material);
}
}
}
//
MeshFilter meshFilter = gameObject.GetComponent<MeshFilter>();
if (meshFilter != null)
{
Mesh mesh = meshFilter.sharedMesh;
if (mesh != null)
{
UnityEngine.Object.Destroy(mesh);
}
}
//
UnityEngine.Object.Destroy(gameObject);
}