DEV Community

Cover image for Addressables Reference Counting: Why Object.Destroy Fails to Free Memory
Toàn Lương Bảo
Toàn Lương Bảo

Posted on Originally published at toanlb.dev on

Addressables Reference Counting: Why Object.Destroy Fails to Free Memory

Addressables Reference Counting: Why Object.Destroy Fails to Free Memory

During memory optimization for medium and large-scale Unity productions, there is an ironic pitfall that catches many engineering teams off guard.

You have just migrated your asset pipeline from legacy Resources to Addressables. Initial benchmarks appear promising: build packages shrink significantly by moving payloads to CDN buckets. But when you tether a physical device to the Unity Profiler, a perplexing phenomenon manifests:
The player slaughters hundreds of enemies, all spawned GameObjects disappear from the hierarchy, yet the application's overall resident RAM footprint fails to drop by a single megabyte. After navigating several consecutive levels, the client begins stuttering until it suddenly crashes from an Out of Memory (OOM) exception.

When auditing the code, developers instinctively insist: "I called Destroy(gameObject) on every defeated monster and expired projectile. Why is memory still pinned?".

The answer lies at the intersection of two fundamentally distinct lifecycle systems: Scene Hierarchy Lifecycles and Addressables' Two-Tier Reference Counting.


1. The Anatomy of Two-Tier Reference Counting in Addressables

Unlike traditional synchronous asset loading where an asset is treated as a detached standalone instance, Addressables organizes assets into a strict, two-tier reference counting model:

flowchart LR
    subgraph TIER1["Tier 1: Asset / Handle RefCount"]
        direction TB
        H1["Handle 1: Prefab A\n(RefCount = 1)"]
        H2["Handle 2: Prefab A\n(RefCount = 1)"]
        SUM_A["Total Asset A RefCount = 2"]
        H1 --> SUM_A
        H2 --> SUM_A
    end

    subgraph TIER2["Tier 2: AssetBundle Container"]
        direction TB
        B_SUM["Bundle Aggregate RefCount = 2"]
        B_NATIVE["Native RAM (LZ4 Archive)\nUnloaded ONLY when RefCount = 0"]
        B_SUM --> B_NATIVE
    end

    SUM_A -->|"Delegates Count"| B_SUM

How the Two Tiers Operate in Harmony

  1. Tier 1 - Asset / Operation Handle RefCount:
    • Every time code invokes Addressables.LoadAssetAsync<T> or Addressables.InstantiateAsync, the system increments that specific asset's RefCount by 1.
    • If five independent subsystems request the exact same asset address, Addressables loads the underlying asset into memory once, but records its RefCount as 5.
    • Calling Addressables.Release(handle) or Addressables.ReleaseInstance(gameObject) decrements that asset's RefCount by 1.
  2. Tier 2 - AssetBundle RefCount:
    • Assets do not float in isolation; they reside physically within an AssetBundle archive.
    • As an individual asset's RefCount increments, the containing AssetBundle's aggregated RefCount increments in lockstep.
    • When an asset's RefCount reaches 0, that individual asset is merely eligible for eviction. However, native RAM is only reclaimed when the aggregate RefCount across all assets within that bundle drops to 0.

2. Why Object.Destroy Fails to Reclaim Native Memory

To understand why Destroy(gameObject) cannot release Addressables memory, we must clearly separate two concepts that are frequently conflated: Scene Instances and Source Native Assets.

flowchart LR
    subgraph SCENE["Scene Hierarchy (C# / C++ Managed Shell)"]
        direction TB
        GO["GameObject Instance\n(Transform, MeshFilter, Collider)"]
        ACT["Call Destroy(gameObject)"]
        GO -->|"Destroyed from Scene"| ACT
    end

    subgraph ENGINE["Addressables Engine (Native RAM)"]
        direction TB
        REF["Addressables RefCount Tracker\n(Receives ZERO Notification!)"]
        BUNDLE["Source Prefab, Texture, Mesh\n(Permanently Pinned in RAM)"]
        REF -->|"Locks in"| BUNDLE
    end

    ACT -.->|"No Communication Bridge"| REF

The Communication Breakdown between Hierarchy and Provider

When you spawn an entity using Addressables.InstantiateAsync("EnemyPrefab"):

  1. Source Asset: Unity streams the source prefab, textures, materials, and meshes from the AssetBundle into native RAM. The RefCount for both the prefab and containing bundle increments to 1.
  2. Scene Instance: Unity clones a new GameObject instance into the active Scene hierarchy so that gameplay components can execute.

When the enemy is eliminated, if developers invoke:
Destroy(enemyInstance);

Here is what actually transpires under the hood:

  • Unity unhooks the GameObject and its components from the Scene hierarchy.
  • The Addressables reference-counting subsystem receives zero notification! The internal RefCount for the source prefab and bundle remains locked at 1.
  • Addressables assumes gameplay is still utilizing the asset, steadfastly preserving the source prefab, 2K textures, meshes, and the entire AssetBundle inside native memory.

Note

Addressables tracks instantiated instances internally via an internal Scene Provider. During a full Scene unload, Addressables sweeps remaining orphaned instances.

However, for single-scene architectures (such as Open World, Roguelike runs, or Endless Runners) or GameObjects marked with DontDestroyOnLoad, assets stranded in this state become permanent native memory leaks.

The Correct Approach: Addressables.ReleaseInstance

Instead of calling Destroy, you must despawn Addressables instances via the dedicated API:
Addressables.ReleaseInstance(enemyInstance);

This performs two operations atomically:

  1. Destroys the GameObject on the active Scene hierarchy identical to Object.Destroy.
  2. Emits an internal decrement event to the Addressables manager, reducing the asset and bundle RefCount so memory can be evicted.

3. The Memory Hostage Trap at the Bundle Level

Even when an entire engineering team rigorously calls Release and ReleaseInstance, memory usage can still refuse to drop.

This occurs when the project falls into the Memory Hostage Trap caused by poor group partitioning.

flowchart LR
    subgraph BUNDLE["Group UI: ui_shared.bundle"]
        direction TB
        A1["Asset 1: ShopAtlas (4MB)\nShop Closed -> RefCount = 0"]
        A2["Asset 2: CoinIcon (15KB)\nActive on HUD -> RefCount = 1"]
        SUM["Bundle Total RefCount = 1\n(Bundle Stays Active)"]
        A1 --> SUM
        A2 --> SUM
    end

    RAM["Native RAM\nRetains Entire ~4.02MB\nShopAtlas Held Hostage!"]

    SUM -->|"Pinned"| RAM

A Classic Scenario: A 15KB Coin Icon Holding a 4MB Sprite Atlas Hostage

Consider this frequent production mistake:

  • The team creates a single Addressable Group named UI_Assets with default settings (Bundle Mode: Pack Together).
  • Inside this group reside:
    1. A 2048x2048 Sprite Atlas weighing 4MB containing item icons for the in-game Shop.
    2. A 32x32 gold coin icon weighing 15KB displayed persistently on the main HUD.
  • The player opens the Shop, purchases an item, and closes it. Gameplay code properly calls Addressables.Release on the Shop Sprite Atlas. The atlas's individual RefCount successfully hits 0.
  • However, the main HUD remains active, displaying the coin icon (RefCount = 1).
  • The Technical Penalty: Because the coin icon is alive, ui_shared.bundle retains an aggregate RefCount of 1. Because the Unity Engine cannot partially unload a compressed archive, the entire 4MB Shop Sprite Atlas remains held hostage in native RAM throughout the entire play session!

One might ask: "Why doesn't Resources.UnloadUnusedAssets() clean this up?".

Under the hood of Unity's C++ Core, while an AssetBundle remains active, its internal asset table holds direct native pointers to all serialized Texture2D objects inside. When Resources.UnloadUnusedAssets() traverses memory, it sees that the texture is anchored by a living AssetBundle, and strictly refuses to unload it.

A 15KB icon locks an asset 300 times its size in memory indefinitely.


4. Hybrid Architecture: Marrying Addressables with Object Pooling

Another misstep when migrating to Addressables is attempting to call Addressables.InstantiateAsync and Addressables.ReleaseInstance for high-frequency entities like machine gun bullets or hit sparks.

If a weapon fires 20 rounds per second, continuous InstantiateAsync calls create severe overhead:

  • Dozens of async task state machines allocate onto the managed heap, inducing constant GC churn.
  • Addressables' handle tracking table updates hundreds of times per second, causing Main Thread CPU contention.

The Production Standard: Load Prefab Once + Conventional Object Pool

To combine CDN streaming capabilities with zero-allocation 60 FPS gameplay, adopt this three-step hybrid workflow:

  1. Load Template Once: Use Addressables.LoadAssetAsync<GameObject> to load the master prefab into memory once. This increments RefCount by 1 for the source prefab.
  2. Clone via Local Pool: Initialize a standard ObjectPool<GameObject>. When spawning projectiles, the pool calls Object.Instantiate(cachedPrefab). These clones are standard Scene instances that do not interact with Addressables' reference counters.
  3. Safe Teardown Pipeline: When leaving the level, purge and destroy all instances in the pool first, then call Addressables.Release on the master prefab handle.
flowchart LR
    subgraph ADDR["Addressables Subsystem"]
        direction TB
        H["AsyncOperationHandle\n(Tracks Master Lifecycle)"]
        P["Master Prefab: PlasmaBullet\n(RefCount = 1)"]
        H --> P
    end

    subgraph POOL["Local Object Pool (In-Memory)"]
        direction TB
        MGR["ObjectPool: Reuse Manager"]
        INST1["Bullet Instance #1"]
        INST2["Bullet Instance #2"]
        INST3["Bullet Instance #3"]
        MGR --> INST1 & INST2 & INST3
    end

    P -->|"Pure C# Object.Instantiate"| MGR

5. Production Implementation and Pure C# Architecture Simulator

Production Code: Pooled Spawner with Addressables and UnityEngine.Pool

Here is a complete production spawner for an Action RPG weapon system, demonstrating asynchronous template loading, pooling via UnityEngine.Pool, and clean lifecycle eviction:

using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.Pool;

public class AddressablePooledSpawner : MonoBehaviour
{
    [SerializeField] private string _bulletAddress = "Weapons/PlasmaBullet";
    private AsyncOperationHandle<GameObject> _prefabHandle;
    private GameObject _cachedPrefab;
    private ObjectPool<GameObject> _bulletPool;
    private bool _isInitialized;
    private bool _isInitializing;

    public async Task InitializePoolAsync(int defaultCapacity = 20, int maxPoolSize = 100)
    {
        if (_isInitialized || _isInitializing) return;
        _isInitializing = true;

        // 1. Load the master prefab template once via Addressables
        _prefabHandle = Addressables.LoadAssetAsync<GameObject>(_bulletAddress);
        _cachedPrefab = await _prefabHandle.Task;

        if (_cachedPrefab == null)
        {
            Debug.LogError($"Failed to load prefab at address: {_bulletAddress}");
            if (_prefabHandle.IsValid())
            {
                Addressables.Release(_prefabHandle);
            }
            _isInitializing = false;
            return;
        }

        // 2. Initialize standard local pool for scene instances
        _bulletPool = new ObjectPool<GameObject>(
            createFunc: () => Instantiate(_cachedPrefab),
            actionOnGet: bullet => bullet.SetActive(true),
            actionOnRelease: bullet => bullet.SetActive(false),
            actionOnDestroy: bullet => Destroy(bullet),
            collectionCheck: false,
            defaultCapacity: defaultCapacity,
            maxSize: maxPoolSize
        );

        _isInitialized = true;
        _isInitializing = false;
    }

    public GameObject SpawnBullet()
    {
        if (!_isInitialized || _bulletPool == null) return null;
        return _bulletPool.Get();
    }

    public void DespawnBullet(GameObject bullet)
    {
        if (_bulletPool == null || bullet == null) return;
        _bulletPool.Release(bullet);
    }

    public void DisposePool()
    {
        if (!_isInitialized) return;

        // MANDATORY: Clear active scene instances before releasing source prefab
        _bulletPool?.Clear();
        _bulletPool = null;

        // Release master prefab handle from Addressables
        if (_prefabHandle.IsValid())
        {
            Addressables.Release(_prefabHandle);
        }

        _cachedPrefab = null;
        _isInitialized = false;
    }

    private void OnDestroy()
    {
        DisposePool();
    }
}
Enter fullscreen mode Exit fullscreen mode

Pure C# Architecture Simulator: Verifying Destroy vs ReleaseInstance

Note

The following pure C# simulation isolates the mechanics of two-tier reference counting. This enables automated unit tests to demonstrate why Destroy fails to decrement reference counts and how memory hostages occur.

using System;
using System.Collections.Generic;
using NUnit.Framework;

public class MockAddressableBundle
{
    public string BundleName { get; }
    public int ReferenceCount { get; private set; }
    public bool IsLoadedInMemory => ReferenceCount > 0;

    public MockAddressableBundle(string name)
    {
        BundleName = name;
        ReferenceCount = 0;
    }

    public void Retain() => ReferenceCount++;
    public void Release()
    {
        if (ReferenceCount <= 0)
            throw new InvalidOperationException($"Bundle '{BundleName}' already has ReferenceCount = 0.");
        ReferenceCount--;
    }
}

public class MockAddressableAsset
{
    public string Address { get; }
    public MockAddressableBundle Bundle { get; }
    public int ReferenceCount { get; private set; }
    public int SizeBytes { get; }

    public MockAddressableAsset(string address, MockAddressableBundle bundle, int sizeBytes)
    {
        Address = address;
        Bundle = bundle;
        SizeBytes = sizeBytes;
        ReferenceCount = 0;
    }

    public void Retain()
    {
        ReferenceCount++;
        Bundle.Retain();
    }

    public void Release()
    {
        if (ReferenceCount <= 0)
            throw new InvalidOperationException($"Asset '{Address}' already has ReferenceCount = 0.");
        ReferenceCount--;
        Bundle.Release();
    }
}

public class MockSceneInstance
{
    public int InstanceId { get; }
    public MockAddressableAsset SourceAsset { get; }
    public bool IsActiveInHierarchy { get; private set; }

    public MockSceneInstance(int instanceId, MockAddressableAsset sourceAsset)
    {
        InstanceId = instanceId;
        SourceAsset = sourceAsset;
        IsActiveInHierarchy = true;
    }

    public void SimulateSceneDestroy()
    {
        IsActiveInHierarchy = false;
    }
}

public class AddressableSimulationEngine
{
    private readonly Dictionary<string, MockAddressableBundle> _bundles = new();
    private readonly Dictionary<string, MockAddressableAsset> _assets = new();
    private readonly Dictionary<int, MockSceneInstance> _trackedInstances = new();
    private int _nextInstanceId = 1;

    public void RegisterAsset(string address, string bundleName, int sizeBytes)
    {
        if (!_bundles.TryGetValue(bundleName, out var bundle))
        {
            bundle = new MockAddressableBundle(bundleName);
            _bundles[bundleName] = bundle;
        }

        _assets[address] = new MockAddressableAsset(address, bundle, sizeBytes);
    }

    public MockAddressableAsset LoadAsset(string address)
    {
        if (!_assets.TryGetValue(address, out var asset))
            throw new KeyNotFoundException($"Asset not found: {address}");

        asset.Retain();
        return asset;
    }

    public void ReleaseAsset(string address)
    {
        if (!_assets.TryGetValue(address, out var asset))
            throw new KeyNotFoundException($"Asset not found: {address}");

        asset.Release();
    }

    public MockSceneInstance Instantiate(string address)
    {
        var asset = LoadAsset(address);
        var instance = new MockSceneInstance(_nextInstanceId++, asset);
        _trackedInstances[instance.InstanceId] = instance;
        return instance;
    }

    // Simulates standard Object.Destroy(gameObject)
    public void NaiveObjectDestroy(MockSceneInstance instance)
    {
        if (instance == null) return;
        instance.SimulateSceneDestroy();
    }

    // Simulates Addressables.ReleaseInstance(gameObject)
    public void AddressablesReleaseInstance(MockSceneInstance instance)
    {
        if (instance == null) return;
        if (!_trackedInstances.ContainsKey(instance.InstanceId))
            throw new InvalidOperationException("Instance does not exist or was already released.");

        instance.SimulateSceneDestroy();
        _trackedInstances.Remove(instance.InstanceId);
        instance.SourceAsset.Release();
    }

    public MockAddressableBundle GetBundle(string bundleName) => _bundles[bundleName];
    public MockAddressableAsset GetAsset(string address) => _assets[address];
}

[TestFixture]
public class AddressableReferenceCountingTests
{
    private AddressableSimulationEngine _engine;

    [SetUp]
    public void SetUp()
    {
        _engine = new AddressableSimulationEngine();
        _engine.RegisterAsset("UI/ShopAtlas", "ui_shared_bundle", 4 * 1024 * 1024);
        _engine.RegisterAsset("UI/CoinIcon", "ui_shared_bundle", 20 * 1024);
        _engine.RegisterAsset("Weapons/PlasmaBullet", "bullet_bundle", 500 * 1024);
    }

    [Test]
    public void Instantiate_IncrementsAssetAndBundleRefCount()
    {
        var instance = _engine.Instantiate("Weapons/PlasmaBullet");

        Assert.IsNotNull(instance);
        Assert.IsTrue(instance.IsActiveInHierarchy);

        var asset = _engine.GetAsset("Weapons/PlasmaBullet");
        var bundle = _engine.GetBundle("bullet_bundle");

        Assert.AreEqual(1, asset.ReferenceCount);
        Assert.AreEqual(1, bundle.ReferenceCount);
        Assert.IsTrue(bundle.IsLoadedInMemory);
    }

    [Test]
    public void NaiveObjectDestroy_LeavesRefCountUnchanged_AndBundlePinnedInMemory()
    {
        var instance = _engine.Instantiate("Weapons/PlasmaBullet");

        _engine.NaiveObjectDestroy(instance);

        Assert.IsFalse(instance.IsActiveInHierarchy);

        var asset = _engine.GetAsset("Weapons/PlasmaBullet");
        var bundle = _engine.GetBundle("bullet_bundle");

        Assert.AreEqual(1, asset.ReferenceCount, "Asset RefCount must remain unchanged after raw Destroy.");
        Assert.AreEqual(1, bundle.ReferenceCount, "Bundle RefCount stays locked at 1.");
        Assert.IsTrue(bundle.IsLoadedInMemory, "Bundle remains pinned in native RAM.");
    }

    [Test]
    public void AddressablesReleaseInstance_DecrementsRefCount_AndUnloadsBundleWhenZero()
    {
        var instance = _engine.Instantiate("Weapons/PlasmaBullet");

        _engine.AddressablesReleaseInstance(instance);

        Assert.IsFalse(instance.IsActiveInHierarchy);

        var asset = _engine.GetAsset("Weapons/PlasmaBullet");
        var bundle = _engine.GetBundle("bullet_bundle");

        Assert.AreEqual(0, asset.ReferenceCount);
        Assert.AreEqual(0, bundle.ReferenceCount);
        Assert.IsFalse(bundle.IsLoadedInMemory, "Bundle must unload when aggregate RefCount reaches 0.");
    }

    [Test]
    public void MemoryHostage_ReleasingShopAtlas_DoesNotUnloadBundleIfCoinIconStillActive()
    {
        var coinIcon = _engine.LoadAsset("UI/CoinIcon");
        var shopAtlas = _engine.LoadAsset("UI/ShopAtlas");

        var bundle = _engine.GetBundle("ui_shared_bundle");
        Assert.AreEqual(2, bundle.ReferenceCount);
        Assert.IsTrue(bundle.IsLoadedInMemory);

        // Releasing ShopAtlas drops individual asset RefCount to 0
        _engine.ReleaseAsset("UI/ShopAtlas");
        Assert.AreEqual(0, shopAtlas.ReferenceCount);

        // Proof of memory hostage: CoinIcon holds the containing bundle hostage
        Assert.AreEqual(1, bundle.ReferenceCount);
        Assert.IsTrue(bundle.IsLoadedInMemory, "All 4MB of ShopAtlas remain locked in RAM!");

        // Only releasing the coin icon unloads the bundle
        _engine.ReleaseAsset("UI/CoinIcon");
        Assert.AreEqual(0, bundle.ReferenceCount);
        Assert.IsFalse(bundle.IsLoadedInMemory, "Bundle only unloads when every contained asset reaches 0.");
    }

    [Test]
    public void DoubleRelease_ThrowsInvalidOperationException()
    {
        var instance = _engine.Instantiate("Weapons/PlasmaBullet");
        _engine.AddressablesReleaseInstance(instance);

        Assert.Throws<InvalidOperationException>(() =>
        {
            _engine.AddressablesReleaseInstance(instance);
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

6. Diagnosing Memory Hostages with Addressables Profiler Module

In earlier Unity versions, developers monitored asset handles using the Addressables Event Viewer. However, beginning with Addressables 2.0 (and in Unity 6), Event Viewer is deprecated and removed.

To inspect memory hostages in modern Unity, use the integrated Addressables Profiler Module:

  1. Enable the Profiler Module:
    • Navigate to Window > Analysis > Profiler.
    • Click Profiler Modules in the upper-left corner and check Addressable Assets.
  2. Prerequisites for Accurate Diagnostics:
    • In Addressables Groups, open Tools > Preferences, and ensure Debug Build Layout is enabled.
    • When entering Play Mode, set Play Mode Script to Use Existing Build (or Simulate Groups). Use Asset Database skips bundle simulation entirely.
  3. Inspect the "Assets not loaded" View:
    • In the Addressable Profiler pane, toggle Assets not loaded.
    • This view isolates assets that reside within bundles currently active in RAM, but whose individual RefCount is currently 0.
    • These are your memory hostages! If you observe a 4MB Sprite Atlas or uncompressed audio clip here, split that asset into an isolated Addressable Group immediately.

7. Lifecycle Strategy Trade-off Matrix

Despawn Strategy Hierarchy Impact RefCount Impact Native RAM Behavior Optimal Use Case
Object.Destroy Immediately removes GameObject Zero effect on RefCount Retains bundle in RAM indefinitely Raw non-Addressable objects only
Addressables.ReleaseInstance Immediately removes GameObject Decrements asset & bundle RefCount Frees bundle when RefCount reaches 0 Isolated instances (Bosses, Maps)
Hybrid: LoadAsset + Pool Toggles active state via SetActive Holds RefCount = 1 for master prefab Fixed template RAM; zero GC churn Bullets, enemy mobs, recurring VFX
Lifecycle Group Splitting No runtime logic changes required Decouples feature RefCounts Permanently prevents memory hostages Segregating HUD, Shop, and Story Cutscenes

8. Production Takeaways

  • The Symmetry Principle: Release with the counterpart API used to load. If loaded via LoadAssetAsync, release with Release(handle). If spawned via InstantiateAsync, release strictly with ReleaseInstance(gameObject). Never call Destroy on Addressable clones.
  • Avoid InstantiateAsync for Rapid Entities: For projectiles, enemy swarms, or floating damage numbers, load the prefab template once via LoadAssetAsync and delegate instance reuse to ObjectPool.
  • Group by Lifecycle Rather than Category: Resist creating monolithic groups like "All UI" or "All Audio". Group according to this rule: "Assets that spawn together and die together belong in the same bundle".
  • Routinely Hunt Memory Hostages: Prior to every release milestone, profile with the Addressables Profiler Module to identify inactive assets pinned inside active bundles.

Top comments (0)