Skip to content

About

AddressablesDirector for Unity: loads and releases Addressables content by owner. Every load names the owner that ends it, loads of the same asset join, and no caller ever releases another caller's reference. Requires UniTask.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

AddressablesDirector

Load Addressables content with an owner. When the owner ends, the content is released.

AddressablesDirector is a Unity package that sits between your game code and Addressables. Every load names the owner that needs the asset, either a CancellationToken or a Component such as your MonoBehaviour. The owner ending is the only release there is: the package has no release call, so your code has no release lines to forget, to run twice or to run for someone else's reference. Loading a key that is already loaded or already loading joins the same load. Every await ends in one of three ways: the asset, an OperationCanceledException when the call was ended on purpose, or an AssetLoadException when it did not work. It never returns null.

Why

Addressables counts references per operation, not per caller. Game code that releases by hand ends up with problems like these, and the package removes each one.

What goes wrong with hand-written release code What AddressablesDirector does
A handle is a struct. Releasing one copy leaves the other copies looking valid, and a double release or a release of someone else's reference is easy to write. Every call makes its own hold with exactly one reference. A hold ends once: when its owner ends, when the loader is disposed, or, for an instance, when the instance is destroyed. No other caller's code can release it.
A view that switches content fast releases the picture on screen before the next one exists, or leaves old loads running. AssetSlot<T> keeps at most one asset, the newest request wins, and the previous asset is released only when the new one is handed over.
A load cannot be stopped midway, and Addressables.InstantiateAsync creates the object even after the caller lost interest. A cancelled call releases its reference at once and its await throws; an instance is never created for a call that ended.
A plain Destroy on a spawned object releases nothing. InstantiateAsync binds the instance to its prefab: Destroy releases it, and the owner ending destroys every instance it spawned.
A failure shows up as a status check, a null result or an Addressables exception that does not say which key failed. A failure is one AssetLoadException with the key, the asset type, the failure kind and a diagnostic id. Nothing stays held.
It is hard to see what is loaded and why. GetHeldAssets() lists every held call with the file and line that made it.
Game code that loads cannot run in a unit test without a real Addressables setup. FakeAssetLoader runs the same ownership rules over in-memory assets.

Requirements

Unity 6000.3 or newer.
UniTask (com.cysharp.unitask) Required. Install it before this package; a package installed from a git URL cannot declare it as a dependency.
Addressables (com.unity.addressables) 4.1.1 Required. It is declared as a dependency, so a git install brings it in.
uGUI (com.unity.ugui) Not needed by the package. The samples need it, and so does your own UI code as usual; Unity's project templates include it.
Test Framework (com.unity.test-framework) Needed only to write tests with the fake loader; Unity's project templates include it.

Install

Install UniTask first. In the Package Manager open the + menu, choose Install package from git URL and enter:

https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask#2.5.11

UniTask documents its other install routes in its own README. Then add AddressablesDirector the same way:

https://github.com/ecanakli/UnityAddressablesDirector.git#v0.1.0

Or add both lines to the dependencies of Packages/manifest.json (the order does not matter):

"com.cysharp.unitask": "https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask#2.5.11",
"com.ecanakli.addressablesdirector": "https://github.com/ecanakli/UnityAddressablesDirector.git#v0.1.0"

Always install a tag, for both packages. Without #v0.1.0 you get whatever the default branch holds at the moment the package resolves. #2.5.11 is a UniTask release tag; UniTask lists its releases on its GitHub page.

Code in the default assembly (no assembly definition) sees the package, UniTask and Addressables with no setup. If your code is in assembly definitions, reference Ecanakli.AddressablesDirector and UniTask, plus Unity.Addressables when your code declares AssetReference fields (and Unity.ResourceManager for IResourceLocation keys). The runtime's public types are in the namespace Ecanakli.AddressablesDirector. The test helpers are in the namespace and assembly Ecanakli.AddressablesDirector.Testing. That assembly is not referenced automatically, so reference it from your test assemblies. It compiles in the Editor without a testables entry, and stays out of player builds that do not include tests; see Testing game code.

Getting started in 5 minutes

Seven steps. Every block is copied from the Thumbnail Tabs sample, which compiles. The sample is a panel with one large picture and five tab buttons; each tab loads its own picture, and tapping tabs fast must never show an old picture or leak one. The blocks leave out their using lines: the types need Ecanakli.AddressablesDirector, Cysharp.Threading.Tasks, UnityEngine, UnityEngine.UI for the view, System for [Serializable] and, for the key field, UnityEngine.AddressableAssets.

1. Create one loader

Create the loader once, when the app starts, from a scene object such as a bootstrap MonoBehaviour's Awake (the sample's ThumbnailTabsBootstrap does), and pass it to the code that loads. It is an IAssetLoader, so the code that uses it never depends on Addressables.

_assets = new AddressablesLoader();

Hand it on:

_view.Init(_assets, new ThumbnailArtService(_catalog));

An AddressablesLoader works in Play Mode and in players, and it is main thread only. Disposing it is optional: it ends whatever is still held.

2. Give the view a slot, and make the view its owner

An AssetSlot<T> holds one asset at a time. The second argument is the owner: pass the MonoBehaviour itself, so destroying the view releases what the slot holds.

private ThumbnailArtService _art;
private AssetSlot<Sprite> _slot;

public void Init(IAssetLoader assets, ThumbnailArtService art)
{
    _art = art;

    // Owned by this view: destroying it releases what the slot holds
    _slot = new AssetSlot<Sprite>(assets, this);
}

Pass the component rather than its destroyCancellationToken: Unity never cancels that token for a component destroyed before it was ever active. See Owners.

3. Load, and assign right after the await

public void Show(string tabId, string title)
{
    // Not awaited: a newer Show supersedes this one through the slot
    ShowAsync(tabId, title).Forget();
}

private async UniTaskVoid ShowAsync(string tabId, string title)
{
    _caption.text = title;
    _spinner.SetActive(true);

    // A superseded call ends at this await; the spinner then belongs to the newer call
    // Assign right after the await: the slot releases the previous picture once this line ran
    _image.sprite = await _art.LoadAsync(_slot, tabId);
    _spinner.SetActive(false);
}

A newer Show cancels the older one: the older await throws OperationCanceledException, which UniTaskVoid ignores, so nothing after the await runs for a call that was replaced. The previous picture is released in the same step that hands over the new one: right after your assignment when the new picture arrives later, and just before the await returns when it was already loaded. No frame renders in between, so the screen never shows a released picture. Never use async void here: it logs the cancellation.

4. Keep keys in a ScriptableObject as AssetReference fields

An AssetReference keeps only a GUID until it is loaded. A direct Sprite field would load its texture together with the ScriptableObject. The sample's catalog uses a direct field for its placeholder on purpose, because the placeholder must always be in memory.

/// <summary>One tab: its id, the title on its button and the picture it shows.</summary>
[Serializable]
public sealed class Entry
{
    [SerializeField] private string _id;
    [SerializeField] private string _title;

    // An AssetReference keeps only a GUID until it is loaded
    [SerializeField] private AssetReferenceSprite _art;

    public string Id => _id;

    public string Title => _title;

    public AssetReferenceSprite Art => _art;
}

An address string, an AssetReference, a label or an IResourceLocation all work as a key. Always load with a concrete asset type such as Sprite.

5. Handle a failure in one place

An AssetLoadException means the load did not work and says why. Catch it where your fallback policy lives, not in every view. In the sample that is a small feature service that returns the placeholder:

// Cancellation is not caught: a superseded or ended request has nothing to show, so it ends the caller too
try
{
    return await slot.LoadAsync(art, callerFile, callerLine);
}
catch (AssetLoadException e)
{
    // The screen shows the placeholder now, so the previous picture is released
    slot.Clear();
    Debug.LogWarning($"[Thumbnail Tabs] '{tabId}' shows the placeholder: {e.Message}");
    return _catalog.Placeholder;
}

Never catch OperationCanceledException in the same place. Addressables also logs its own error next to a real load failure; the package adds no error log of its own for it.

6. Set up the sample content and press Play

Import the sample from the Package Manager (see Samples), run Tools/AddressablesDirector/Samples/Set Up Thumbnail Tabs Content, open the scene and press Play. The Held text lists GetHeldAssets(): tap the picture tabs as fast as you like, and once the last picture is on screen it shows one row, that picture (the Broken tab shows the placeholder and zero rows). Stop Play and everything is released, with no release line in the code.

7. Read on

Getting started goes through the same code slowly, including the three outcomes of an await and the await-once rule. Owners is the page to read before you write your first load.

The rule and four concepts

The rule: every load names its owner, and the owner ending is the only release. There is no release line.

  1. The loader. IAssetLoader is the one door. AddressablesLoader is the implementation over Addressables; FakeAssetLoader is the one for tests.
  2. The owner. A cancellable CancellationToken or a Component. Use a MonoBehaviour for a view, a CancellationTokenSource you cancel for an area or a session, and Application.exitCancellationToken for the life of the app. CancellationToken.None throws, because it can never end.
  3. The hold. Every call makes one hold with one reference. A key already loaded or loading joins the same load, and one owner ending never takes the asset from another owner.
  4. The three outcomes. The asset; OperationCanceledException when the call was ended on purpose (its owner ended, a newer slot request replaced it, the loader or the app shut down), carrying the owner's token when the owner ended it; AssetLoadException when it did not work. Never null.

Samples

Import a sample from the Package Manager: select AddressablesDirector, open Samples and press Import. Each sample ships a menu item that adds its content to Addressables (it creates the Addressables settings only if the project has none, and only when you click it). Run it before the scene. All three need uGUI and UniTask. They use the Input System for UI input when it is installed and enabled, and the Input Manager otherwise; neither needs setting up.

Sample Content setup Shows
Thumbnail Tabs Tools/AddressablesDirector/Samples/Set Up Thumbnail Tabs Content Switching content fast with an AssetSlot, keys from a ScriptableObject with AssetReference fields, and a feature service that owns the fallback.
Preload With Progress Tools/AddressablesDirector/Samples/Set Up Preload With Progress Content A loading screen that preloads an area by label with a progress bar and a Cancel button, and areas that own what they loaded.
Spawn Prefabs Tools/AddressablesDirector/Samples/Set Up Spawn Prefabs Content Instances owned by a spawner, a plain Destroy as the whole release, and many copies from one loaded prefab.

Limits in brief

  • Main thread only. Calls from another thread throw ADDRDIR102; only Dispose and an owner cancelled on another thread are moved to the main thread. See Threading.
  • Play Mode and players. An AddressablesLoader created in the Editor outside Play Mode throws ADDRDIR106.
  • Memory returns per AssetBundle. An asset's memory comes back when every hold on every asset of its bundle has ended, so your group layout decides what ending an area frees. See Memory and bundles.
  • Loader tasks are awaited once. A second await while the load is still pending throws InvalidOperationException; .Preserve() allows several. Slot tasks may be awaited several times.
  • A CancellationTokenSource disposed without Cancel cannot end its holds. Always cancel before you dispose. See Owners.
  • A failure leaves a short window. If another owner loads the same key between a failure and the destruction of the failed operation, later loads of that key may start another operation instead of joining it. Nothing leaks. See Architecture.
  • Create a FakeAssetLoader inside each test. One built in Edit Mode and kept across a Play Mode change may stop running its per-frame work. See Testing game code.
  • No download management in 0.1.0. Remote bundles load through your normal Addressables settings, and they need a nonzero Bundle Request Timeout in the Addressables settings. Download size, predownload with byte progress, content updates through the package, pooling, additive scenes and URL images are planned for later versions. See Remote content in 0.1.0.
  • Version 0.1.0. What it adds is in the changelog.

Diagnostics are ADDRDIR101 to ADDRDIR106, ADDRDIR201 to ADDRDIR207 and ADDRDIR301 to ADDRDIR308; each has a section in Troubleshooting.

Documentation

The same grouping is on the documentation home.

Start here

  • Getting started: install, the loader, a first load, the three outcomes, assign right after the await
  • Owners: every kind of owner, areas, app lifetime, component owners, a source disposed without cancel

Guides

  • Switching content: AssetSlot<T>, newest wins, the feature service, keeping a tab set loaded
  • Preloading: LoadAllAsync, labels, progress, all or nothing, cancel
  • Instances: InstantiateAsync, Destroy as the release, clones, many copies from one prefab
  • Memory and bundles: where memory returns, AssetReference against direct references, GetHeldAssets, remote content
  • Threading: main thread only, owners cancelled on another thread, await once
  • Testing game code: FakeAssetLoader, FakePendingLoad, Play Mode tests against real Addressables

Reference

Design

  • Architecture: holds, the source boundary, release order, guarantees and their limits
  • ADR-001: Every call names its owner, and there is no release API
  • ADR-002: Joins come from the Addressables cache, and one hold owns exactly one reference
  • ADR-003: One loader per app; content areas are owners, not lists
  • ADR-004: One Addressables initialisation per Play session, shared and never released; a failure is permanent
  • ADR-005: Every await ends in one of three outcomes
  • ADR-006: Instances are owned objects: our own load, a plain instantiate and a hidden binding
  • ADR-007: Sets are all or nothing, over one child hold per asset
  • ADR-008: The Editor tears loaders down when Play Mode starts to exit, inside the runtime assembly
  • ADR-009: Component owners, backed by a polled death watch
  • ADR-010: A failure reaches the caller only after the failed operation is destroyed
  • ADR-011: Ambiguous means distinct assets, not distinct locations
  • ADR-012: Loads go through the resource manager's untracked call
  • ADR-013: The slot releases the old asset in the step that delivers the new one
  • ADR-014: Main thread only; off-thread cancels and disposes are moved to the main thread
  • ADR-015: No container, scope type or static facade; the loader is passed in
  • ADR-016: Remote content control is deferred; 0.1.0 requires a nonzero request Timeout
  • ADR-017: Loader tasks are awaited once

For AI tools, llms.txt holds a summary, the rules that bite and a one-line description of every page in reading order, and llms-full.txt is the whole documentation in one file.

License

MIT. See LICENSE.md.

About

AddressablesDirector for Unity: loads and releases Addressables content by owner. Every load names the owner that ends it, loads of the same asset join, and no caller ever releases another caller's reference. Requires UniTask.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages