Heapshot (Pro only)

_Supported platforms: Mac/PC Standalone player, iOS, Xbox360, PS3._

_Note: doesn't work with Script Debugging enabled._

This utility captures a heapshot and shows all managed objects which are currently _alive_. It also shows references and back-trace references between objects. This helps easily identify why are some objects not being collected by the garbage collector. Heapshot uses profiler for data sending, thus the profiler needs to be enabled.

alloc3.jpg

Build the player and launch it. Then go in editor go to Windows→Heapshot, a window similar to profiler will open. Click on _Active Profiler_ to select the target you'll be examining, ignore the _Editor_ selection, as you can't capture heapshot from the editor. Now click on _Capture heapshot_.

_Note: if you're capturing heapshot from Mac/PC standalone, you have to give focus to player window, as only then the heapshot data will be sent to editor, so in short switch to player's window and then back to Editor._

The test script which was used while capturing heapshot:

public class TestingHeapshot : MonoBehaviour 
{
    public class StaticClass
    {
        int someData;
    }
    public class DynamicClass
    {
        int someData;
    }
 
    private static StaticClass staticClass = new StaticClass();
    private DynamicClass dynamicClass = null;
 
    void OnGUI()
    {
        if (GUILayout.Button("Allocate")) dynamicClass = new DynamicClass();
        if (GUILayout.Button("Free")) dynamicClass = null;
    }
}
 
 

You should see something like this:

alloc1.jpg

In the left side you should see two tabs:

  • Roots - these are statically created objects, which aren't referenced by anything and are always _alive_.
  • Objects - here you can see all the objects which are currently _alive_, because they're are either referenced by a static object or by Unity engine itself, this usually applies for UnityEngine.* classes.

On the left side, I've selected the object of type _TestingHeapshot/StaticClass_, the field name says (Unknown) because one object can be referenced by multiple fields, so it's impossible to name a field to which the object belongs.

On the right side, we can see that our object is referenced by _staticClass_ field, that's why it is _alive_ and not being collected by the garbage collector.

There are no objects of _TestingHeapshot/DynamicClass_ type currently.

But if we would execute:

 dynamicClass = new DynamicClass(); 

and capture a heapshot, we would see:

alloc2.jpg

We can see that _TestingHeapshot/DynamicClass_ is being referenced by _dynamicClass_ field in _TestingHeapshot_ class, moving along references we see that _TestingHeapshot_ is being referenced by _<Unity>_, this is because _TestingHeapshot_ is a _MonoBehaviour_ and it's attached to a game object, so Unity references that object until the component _TestingHeapshot_ is removed from the game object.

Good luck finding those leaks !