はじめに
UnityのAddressables について
- 便利そうだけどまったく使えていない。
- とりあえず、とっかかりだけ知りたい。
と思ったので簡単にまとめた記事になります。
- Unity 2020.3.27
- Addressables 1.18.19
Addressables とは
Addressables
はResources
やAssetBundle
の良いとこ取りをしたシステムです。Unity2018.2から使えるようになりました。
導入
Package Manager
ウインドウでPackages: Unity Registry
に変更してAddressables
を探してInstall
します。

インストールが完了したらWindow
>Asset Management
>Addressables
>Groups
でウィンドウを開きCreate Addressables Settings
を押します。

そうするとAssetsフォルダ直下にAddressableAssetsData
フォルダができます。Addressables関連の設定はここに保存されます。
また、Addressablesのインストール以降はInspector
の上部にAddressable
チェックボックスが表示されるようになります。これをチェックすることでAddressablesで管理する素材になります。

ローカルからロードしてみる
導入が済んだら、さっそく画像をAddressable素材にしてスクリプトからUIを動的に差し替えてみます。
- ちなみに画像素材はこちらのアセットを使用しました。
任意の画像を選択してInspector
でAddressable
にチェクを入れると右側にパスが自動で入ります。ただ、これが画像を呼び出す文字列になるので管理しやすいように変更します。ここでは「Spades.png」としました。

Window
>Asset Management
>Addressables
>Groups
からAddressables Groups
ウインドウを開きます(先の文字列はこちらでも変更できます)

Play Mode Script
をUse Asset Database
にします。

次に画像をロードしてUIに反映するスクリプトを用意します。
using UnityEngine;
using UnityEngine.AddressableAssets;//Addressablesを使うのに必要
using UnityEngine.UI;//UIを使うのに必要
public class AddressableSample : MonoBehaviour
{
[SerializeField] Image Img;
async void Start()
{
//Spriteをロードする
var sprite = await Addressables.LoadAssetAsync<Sprite>("Spades.png").Task;
//UIに反映
Img.sprite = sprite;
//使い終わったらメモリから開放する
//Addressables.Release(sprite); <<今回は使わない
}
}
スクリプトが出来たら適当なオブジェクトに貼り付けてImageをアサインします。
Playモードで画像が差し替えられることを確認します。

リモートからロードしてみる
Addressablesの真骨頂。サーバーにアップされた素材をスクリプトから動的に差し替えてみます。
- 読み込み先を変更するだけです。先に用意したスクリプトはそのまま。
Addressables Groups
ウインドウでDefault Local Group
を選択します。Inspector
でBuildPath
をRemoteBuildPath
にします。- 同じく
Inspector
でLoadPath
をRemoteLoadPath
にします。

Window
>Asset Management
>Addressables
>Settings
からAddressable Asset Settings
を開きます。
Player Version Override
に管理しやすい文字列を入れます。ここでは「a1」としました。Build Remote Catalog
をチェックします。BuildPath
をRemoteBuildPath
にします。LoadPath
をRemoteLoadPath
にします。

Addressables Groups
ウインドウに戻ってBuild
>New Build
>Default Build Script
でアセットバンドルをビルドします。

問題なければプロジェクトファイルの中にServerDataフォルダが作成され、下記3つのファイルが書き出されているはずです。
- catalog_xx.hash
- catalog_xx.json
- defaultlocalgroup_assets_all_xxxx.bundle
catalog
は素材の依存関係情報と、その変更チェック用のファイルです。.bundle
は素材その物を圧縮したファイルです。

レンタルサーバーやクラウドストレージなどに3つのファイルをアップロードします。

Unityに戻りWindow
>Asset Management
>Addressables
>Profiles
を選択してAddressables Profiles
を開きます。RemoteLoadPath
を先の3ファイルをアップしたURLに変更します。

Addressables Groups
ウインドウのPlay Mode Script
をUse Existing Build
に変更します。Use Existing Build
にすることでアセットバンドルから素材を読み込むようになります。

Playモードで画像が差し替えられることを確認します。

サーバーの素材を変更してみる
ストアでアプリを更新しなくても中身を変更できるのがAddressablesの大きな利点なので、ついでにそれも試してみます。
- アプリをリリース済みの想定で、読み込み先もスクリプトもそのまま。アセットバンドルだけビルドし直してサーバーの素材を変更します。

先程と別の画像の文字列を「Spades .png」にします。

あとは先に行った手順を繰り返します。
Addressables Groups
ウインドウでBuild
>New Build
>Default Build Script
でアセットバンドルをビルドします。- 書き出された3つのファイルをサーバーへアップします。
Playモードで画像が差し替えられることを確認します。

以上です。
参考



