Unity の C# コードからアプリのアセットパックにアクセスするには、このガイドの手順を実施します。アセットパックで App Bundle をビルドしていない場合は、この先に進む前に Unity 向けのビルドを確認してください。
概要
Play Asset Delivery Unity API には、アセットパックのリクエスト、ダウンロードの管理、アセットへのアクセスを行うための機能が用意されています。API で使用する関数は、アセットパックの作成方法によって異なります。
プラグイン UI を使用してアセットパックを作成した場合は、プラグイン設定アセットパック を選択してください。
API(またはプラグイン UI)を使用してアセットパックを作成した場合は、API 設定アセットパックを選択してください。
API は、アクセスするアセットパックの配信タイプにかかわらず、ほぼ同じです。アセットパックにアクセスする手順を次のフローチャートに示します。
図 1. アセットパックへのアクセスのフロー図
アセットパックを取得する
ディスク上で最新バージョンのアセットパックをまだ利用できない場合は、Play Asset Delivery ライブラリをインポートし、RetrieveAssetPackAsync()
メソッドを呼び出してアセットパックをダウンロードします。
using Google.Play.AssetDelivery; // After download, the assets and/or AssetBundles contained in the asset pack // are not loaded into memory. PlayAssetPackRequest request = PlayAssetDelivery.RetrieveAssetPackAsync(assetPackName);
インストール時の配信
install-time
として設定されたアセットパックは、アプリの起動時にすぐ利用できますが、アセットをメモリに読み込む必要があります。アセットをメモリに読み込むをご覧ください。
fast-follow 配信と on-demand 配信
以下のセクションは、fast-follow
アセットパックと on-demand
アセットパックに適用されます。
ステータスを確認する
各アセットパックは、アプリの内部ストレージ内の個別のフォルダに保存されます。アセットパックがすでにダウンロードされて利用可能になっているか、またはエラーが発生したかを判別するには、isDone()
メソッドを使用します。
ダウンロードをモニタリングする
リクエストのステータスをモニタリングするには、PlayAssetPackRequest
オブジェクトをクエリします。
// 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 does not mean that the request has completed, only that // the DOWNLOADING stage is finished. float progress = request.DownloadProgress; // Returns the status of the retrieval request. // If the request completed successfully, this value should be AssetDeliveryStatus.Available. // If an error occurred, this value should be AssetDeliveryStatus.Failed. AssetDelivery status = request.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.Failed: // Asset pack retrieval failed. case AssetDeliveryStatus.WaitingForWifi: // Asset pack retrieval paused until either the device connects via Wi-Fi, // or the user accepts the PlayAssetDelivery.ShowCellularDataConfirmation dialog. default: break; } // Returns true if status is AssetDeliveryStatus.Available or AssetDeliveryStatus.Failed. bool done = request.IsDone; // If AssetDeliveryStatus.Failed, find more info about the error. AssetDeliveryErrorCode error = request.Error;
大規模なダウンロード
150 MB を超えるアセットパックは、デバイスが Wi-Fi に接続されている場合にのみ、自動でダウンロードできます。ユーザーが Wi-Fi に接続していない場合、PlayAssetPackRequest
ステータスは AssetDeliveryStatus.WaitingForWifi
に設定され、ダウンロードは一時停止されます。この場合は、デバイスが Wi-Fi に接続されるのを待ってダウンロードを再開するか、またはモバイル接続でパックをダウンロードするための承認をユーザーに求めます。
if(request.Status == AssetDeliveryStatus.WaitingForWifi) { var userConfirmationOperation = PlayAssetDelivery.ShowCellularDataConfirmation(); 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. In this case, we recommend // developers wait for Wi-Fi before attempting to download again. // You can get more info by calling GetError() on the operation. case ConfirmationDialogResult.Accepted: // User accepted the confirmation dialog - download will start // automatically (no action needed). case ConfirmationDialogResult.Declined: // User canceled or declined the dialog. Await Wi-Fi connection, or // re-prompt the user. default: break; } }
リクエストをキャンセルする(on-demand のみ)
アセットパックがダウンロードされる前にリクエストをキャンセルする必要がある場合は、PlayAssetPackRequest
オブジェクトの AttemptCancel()
メソッドを呼び出します。
// Will only attempt if the status is Pending, Retrieving, or Available - otherwise // it will be a no-op. request.AttemptCancel(); // Check to see if the request was successful by checking if the error code is Canceled. if(request.Error == AssetDeliveryErrorCode.Canceled) { // Request was successfully canceled. }
アセットをメモリに読み込む
リクエストが完了したら、次のいずれかの関数を使用してアセットをメモリに読み込みます。
PlayAssetPackRequest.GetAssetLocation()
を使用してAssetLocation
オブジェクトを取得します。このオブジェクトにより、ディスクからアセットを読み込むためのアセットのパス、オフセット、サイズが提供されます。- アセットが AssetBundle である場合は、
PlayAssetPackRequest.LoadAssetBundleAsync(assetPath)
コンビニエンス メソッドを使用できます。メソッドに渡すアセットパスは、アセットパック内の AssetBundle へのパスに対応している必要があります。これにより、AssetBundleCreateRequest が返されます。
非同期でアセットパックをリクエストする
ほとんどの場合、コルーチンを使用して非同期でアセットパックをリクエストし、進行状況をモニタリングする必要があります。以下をご覧ください。
private IEnumerator LoadAssetPackCoroutine(string assetPackName) { PlayAssetPackRequest request = PlayAssetDelivery.RetrieveAssetPackAsync(assetPackName); while (!request.IsDone) { if(request.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(() => request.Status != AssetDeliveryStatus.WaitingForWifi); } // Use request.DownloadProgress to track download progress. // Use request.Status to track the status of request. yield return null; } if (request.Error != AssetDeliveryErrorCode.NoError) { // There was an error retrieving the pack. 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. Load the asset pack into memory. AssetBundleCreateRequest assetBundleCreateRequest = request.LoadAssetBundleAsync(path/to/exampleBundle); yield return assetBundleCreateRequest; AssetBundle assetBundle = assetBundleCreateRequest.assetBundle;
エラー処理の詳細については、エラーコードのリストをご覧ください。
その他の Play Core API メソッド
アプリで使用できるその他の API メソッドを次にいくつか示します。
複数のアセットパックを取得する
一度に複数のアセットパックを取得するには、次の関数を使用します。
// assetPackNames is an array of strings corresponding to asset packs. PlayAssetPackBatchRequest batchRequest = PlayAssetDelivery.RetrieveAssetPackBatchAsync(<IListstring> assetPackNames);
個別のリクエストのステータスをモニタリングするには、状態の Dictionary
を調べます。
// Dictionary of AssetPackStates, with the asset pack name as the key. Dictionary<string, PlayAssetPackRequest> requests = batchRequest.Requests; // Returns true if all requests are complete. bool requestComplete = batchRequest.IsDone;
ダウンロード サイズを確認する
アセットパックのサイズを確認するには、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 アセットパックと on-demand アセットパックは削除できます。次の非同期呼び出しを行い、呼び出しが完了したときのコールバック メソッドを設定します。
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 でアセット配信をテストします。