アセット配信を統合する(Unity)

アセット配信を統合する場合、Unity ゲームは Addressables または AssetBundle を使用してアセットパックにアクセスできます。Addressables は Unity 2019.4 以降でビルドされたゲーム用に推奨される最新のアセット送付ソリューションで、AssetBundle は Unity 2017.4 および 2018.4 のアセットパックをサポートしています。

Unity Addressables

Unity 2019.4 以降でビルドされたゲームは、Android でのアセット送付に Addressables を使用してください。Unity は Addressables を使用した Android アセットパックの処理用に Play Asset Deliver(PAD)API を用意しています。Addressables の使用について詳細は、以下をご覧ください。

AssetBundle ファイルを使用する

Unity 2017.4 および 2018.4 でビルドされたゲームでは、Android でのアセット配信に AssetBundle ファイルを使用できます。Unity AssetBundle ファイルにはシリアル化されたアセットが含まれており、アプリの実行中に Unity エンジンに読み込めます。これらのファイルはプラットフォーム固有(Android 用など)に作成され、アセットパックと組み合わせて使用できます。ほとんどの場合、1 つの AssetBundle ファイルが 1 つのアセットパックにパッケージ化され、そのアセットパックは AssetBundle と同じ名前を使用します。アセットパックをより柔軟に作成するには、API を使用してアセットパックを設定します。

実行時に、Unity の Play Asset Delivery クラスを使用して、アセットパックにパッケージ化された AssetBundle を取得します。

前提条件

  1. Play Asset Delivery Unity Plugin の最新リリースを Unity 用の Google パッケージからダウンロードします。

  2. Unity で AssetBundle を作成します

UI を使用して AssetBundle を設定する

  1. アセットパック内の各 AssetBundle を設定します。

    1. [Google] > [Android App Bundle] > [Asset Delivery Settings] を選択します。
    2. AssetBundle ファイルを直接含むフォルダを選択するために、[Add Folder] をクリックします。

  2. バンドルごとに [Delivery Mode] を [Install Time]、[Fast Follow]、[On Demand] のいずれかに変更します。エラーや依存関係を解決し、ウィンドウを閉じます。

  3. [Google] > [Build Android App Bundle] を選択して App Bundle をビルドします。

  4. (省略可)さまざまなテクスチャ圧縮形式をサポートするように App Bundle を構成します。

API を使用してアセットパックを設定する

自動ビルドシステムの一部として実行できるエディタ スクリプトを使用して Asset Delivery を設定できます。

AssetPackConfig クラスを使用して、Android App Bundle ビルドに含めるアセットと、アセットの配信モードを定義します。これらのアセットパックに AssetBundle を含める必要はありません。

public void ConfigureAssetPacks {
   // Creates an AssetPackConfig with a single asset pack, named
   // examplePackName, containing all the files in path/to/exampleFolder.
   var assetPackConfig = new AssetPackConfig();
   assetPackConfig.AddAssetsFolder("examplePackName",
                                   "path/to/exampleFolder",
                                   AssetPackDeliveryMode.OnDemand);

   // Configures the build system to use the newly created assetPackConfig when
   // calling Google > Build and Run or Google > Build Android App Bundle.
   AssetPackConfigSerializer.SaveConfig(assetPackConfig);

   // Alternatively, use BundleTool.BuildBundle to build an App Bundle from script.
   BuildBundle(new buildPlayerOptions(), assetPackConfig);
}

Bundletool クラスの BuildBundle 静的メソッドを使用し、BuildPlayerOptionsAssetPackConfig に応じて、Android App Bundle とアセットパックを生成します。

ガイド チュートリアルについては、Unity ゲームでの Play Asset Delivery の使用に関する Codelab をご覧ください。

Play Asset Delivery Unity API と統合する

Play Asset Delivery Unity API には、アセットパックのリクエスト、ダウンロードの管理、アセットへのアクセスを行うための機能が用意されています。まずプロジェクトに Unity プラグインを追加してください。

API で使用する関数は、アセットパックの作成方法によって異なります。

プラグイン UI を使用してアセットパックを作成した場合は、プラグイン設定アセットパックを選択してください。

API(またはプラグイン UI)を使用してアセットパックを作成した場合は、API 設定アセットパックを選択してください。

アクセスするアセットパックの配信タイプに応じて API を実装します。アセットパックにアクセスする手順を次のフローチャートに示します。

プラグインによるアセットパックへのアクセスのフロー図

図 1. アセットパックへのアクセスのフロー図

AssetBundle を取得する

AssetBundle を取得するには、Play Asset Delivery ライブラリをインポートし、RetrieveAssetBundleAsync() メソッドを呼び出します。

using Google.Play.AssetDelivery;

// Loads the AssetBundle from disk, downloading the asset pack containing it if necessary.
PlayAssetBundleRequest bundleRequest = PlayAssetDelivery.RetrieveAssetBundleAsync(asset-bundle-name);

インストール時の配信

install-time として設定されたアセットパックは、アプリの起動時にすぐ利用できます。AssetBundle からシーンを読み込むには、以下を使用します。

AssetBundle assetBundle = bundleRequest.AssetBundle;

// You may choose to load scenes from the AssetBundle. For example:
string[] scenePaths = assetBundle.GetAllScenePaths();
SceneManager.LoadScene(scenePaths[path-index]);

fast-follow 配信と on-demand 配信

以下のセクションは、fast-follow アセットパックと on-demand アセットパックに適用されます。

ステータスを確認する

各アセットパックは、アプリの内部ストレージ内の個別のフォルダに保存されます。アセットパックがすでにダウンロードされているかどうかを判別するには、isDownloaded() メソッドを使用します。

ダウンロードをモニタリングする

リクエストのステータスをモニタリングするには、PlayAssetBundleRequest オブジェクトをクエリします。

// Download progress of request, between 0.0f and 1.0f. The value will always be
// 1.0 for assets delivered as install-time.
// NOTE: A value of 1.0 will only signify the download is complete. It will still need to be loaded.
float progress = bundleRequest.DownloadProgress;

// Returns true if:
//   * it had either completed the download, installing, and loading of the AssetBundle,
//   * OR if it has encountered an error.
bool done = bundleRequest.IsDone;

// Returns status of retrieval request.
AssetDeliveryStatus status = bundleRequest.Status;
switch(status) {
    case AssetDeliveryStatus.Pending:
        // Asset pack download is pending - N/A for install-time assets.
    case AssetDeliveryStatus.Retrieving:
        // Asset pack is being downloaded and transferred to app storage.
        // N/A for install-time assets.
    case AssetDeliveryStatus.Available:
        // Asset pack is downloaded on disk but NOT loaded into memory.
        // For PlayAssetPackRequest(), this indicates that the request is complete.
    case AssetDeliveryStatus.Loading:
        // Asset pack is being loaded.
    case AssetDeliveryStatus.Loaded:
        // Asset pack has finished loading, assets can now be loaded.
        // For PlayAssetBundleRequest(), this indicates that the request is complete.
    case AssetDeliveryStatus.Failed:
        // Asset pack retrieval has failed.
    case AssetDeliveryStatus.WaitingForWifi:
        // Asset pack retrieval paused until either the device connects via Wi-Fi,
        // or the user accepts the PlayAssetDelivery.ShowConfirmationDialog dialog.
    case AssetDeliveryStatus.RequiresUserConfirmation:
        // Asset pack retrieval paused until the user accepts the
        // PlayAssetDelivery.ShowConfirmationDialog dialog.
    default:
        break;
}

大規模なダウンロード

200 MB を超えるアセットパックは Wi-Fi 接続時のみ自動的にダウンロードできます。ユーザーが Wi-Fi に接続していない場合、PlayAssetBundleRequest ステータスは AssetDeliveryStatus.WaitingForWifi に設定され、ダウンロードは一時停止されます。この場合は、デバイスが Wi-Fi に接続されるのを待ってダウンロードを再開するか、またはモバイル接続でパックをダウンロードするための承認をユーザーに求めます。

ユーザーによる確認が必要

パックのステータスが AssetDeliveryStatus.RequiresUserConfirmation の場合、PlayAssetDelivery.ShowConfirmationDialog() で表示されるダイアログをユーザーが同意するまで、ダウンロードは続行されません。このステータスは、アプリが Play で認識されない場合に発生することがあります。この場合、PlayAssetDelivery.ShowConfirmationDialog() を呼び出すと、アプリが更新されます。更新が完了したら、アセットをもう一度リクエストしてください。

if(request.Status == AssetDeliveryStatus.RequiresUserConfirmation
   || request.Status == AssetDeliveryStatus.WaitingForWifi) {
    var userConfirmationOperation = PlayAssetDelivery.ShowConfirmationDialog();
    yield return userConfirmationOperation;

    switch(userConfirmationOperation.GetResult()) {
        case ConfirmationDialogResult.Unknown:
            // userConfirmationOperation finished with an error. Something went
            // wrong when displaying the prompt to the user, and they weren't
            // able to interact with the dialog.
        case ConfirmationDialogResult.Accepted:
            // User accepted the confirmation dialog--an update will start.
        case ConfirmationDialogResult.Declined:
            // User canceled or declined the dialog. It can be shown again.
        default:
            break;
    }
}

リクエストをキャンセルする(on-demand のみ)

AssetBundle がメモリに読み込まれる前にリクエストをキャンセルする必要がある場合は、PlayAssetBundleRequest オブジェクトの AttemptCancel() メソッドを呼び出します。

// Will only attempt if the status is Pending, Retrieving, or Available - otherwise
// it will be a no-op.
bundleRequest.AttemptCancel();

// Check to see if the request was successful by checking if the error code is Canceled.
if(bundleRequest.Error == AssetDeliveryErrorCode.Canceled) {
    // Request was successfully canceled.
}

非同期でアセットパックをリクエストする

ほとんどの場合、コルーチンを使用して非同期でアセットパックをリクエストし、進行状況をモニタリングする必要があります。以下をご覧ください。

private IEnumerator LoadAssetBundleCoroutine(string assetBundleName) {

    PlayAssetBundleRequest bundleRequest =
        PlayAssetDelivery.RetrieveAssetBundleAsync(assetBundleName);

    while (!bundleRequest.IsDone) {
        if(bundleRequest.Status == AssetDeliveryStatus.WaitingForWifi) {
            var userConfirmationOperation = PlayAssetDelivery.ShowCellularDataConfirmation();

            // Wait for confirmation dialog action.
            yield return userConfirmationOperation;

            if((userConfirmationOperation.Error != AssetDeliveryErrorCode.NoError) ||
               (userConfirmationOperation.GetResult() != ConfirmationDialogResult.Accepted)) {
                // The user did not accept the confirmation. Handle as needed.
            }

            // Wait for Wi-Fi connection OR confirmation dialog acceptance before moving on.
            yield return new WaitUntil(() => bundleRequest.Status != AssetDeliveryStatus.WaitingForWifi);
        }

        // Use bundleRequest.DownloadProgress to track download progress.
        // Use bundleRequest.Status to track the status of request.

        yield return null;
    }

    if (bundleRequest.Error != AssetDeliveryErrorCode.NoError) {
        // There was an error retrieving the bundle. For error codes NetworkError
        // and InsufficientStorage, you may prompt the user to check their
        // connection settings or check their storage space, respectively, then
        // try again.
        yield return null;
    }

    // Request was successful. Retrieve AssetBundle from request.AssetBundle.
    AssetBundle assetBundle = bundleRequest.AssetBundle;

エラー処理の詳細については、AssetDeliveryErrorCodes のリストをご覧ください。

その他の Play Core API メソッド

アプリで使用できるその他の API メソッドを次にいくつか示します。

ダウンロード サイズを確認する

AssetBundle のサイズを確認するには、Google Play に対して非同期呼び出しを行い、オペレーションが完了したときのコールバック メソッドを設定します。

public IEnumerator GetDownloadSize() {
   PlayAsyncOperation<long> getSizeOperation =
   PlayAssetDelivery.GetDownloadSize(assetPackName);

   yield return getSizeOperation;
   if(operation.Error != AssetDeliveryErrorCode.NoError) {
       // Error while retrieving download size.
    } else {
        // Download size is given in bytes.
        long downloadSize = operation.GetResult();
    }
}

AssetBundle を削除する

メモリに現在読み込まれていない fast-follow AssetBundle と on-demand AssetBundle は削除できます。次の非同期呼び出しを行い、呼び出しが完了したときのコールバック メソッドを設定します。

PlayAsyncOperation<string> removeOperation = PlayAssetDelivery.RemoveAssetPack(assetBundleName);

removeOperation.Completed += (operation) =>
            {
                if(operation.Error != AssetDeliveryErrorCode.NoError) {
                    // Error while attempting to remove AssetBundles.
                } else {
                    // Files were deleted OR files did not exist to begin with.
                }
            };

次のステップ

ローカルおよび Google Play でアセット配信をテストします。