集成 Asset Delivery (Unity)

使用集合让一切井井有条 根据您的偏好保存内容并对其进行分类。

按照本指南中的步骤,从 Unity C# 代码获取应用的资源包。如果您尚未使用资源包构建 app bundle,请参阅针对 Unity 构建后再继续。

概览

Play Asset Delivery Unity API 提供了用于请求资源包、管理下载内容和获取资产的功能。您在该 API 中使用的函数取决于您创建资源包的方式。

如果您使用插件界面创建资源包,请选择插件配置的资源包

如果您使用 API(或插件界面)创建资源包,请选择 API 配置的资源包

无论您希望获取的资源包的分发类型为何,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-followon-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;

下载内容较大

超过 150MB 的资源包可以自动下载,但前提是设备必须已连接到 WLAN。如果用户未连接到 WLAN,PlayAssetPackRequest 状态会设置为 AssetDeliveryStatus.WaitingForWifi,下载也会暂停。在这种情况下,要么等到设备连接到 WLAN 再恢复下载,要么提示用户批准通过移动网络连接下载资源包。

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;
    }
}

取消请求(仅限按需)

如果您在资源包下载前需要取消请求,请对 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.
}

将资产加载到内存中

请求完成后,请使用以下函数之一将资产加载到内存中:

异步请求资源包

在大多数情况下,您应使用协程异步请求资源包并监控进度,如下所示:

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

您可以移除当前未加载到内存中的快速跟进式分发和按需分发资源包。发出以下异步调用,并针对何时完成设置回调方法:

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 测试 Asset Delivery 情况