Mengintegrasikan pengiriman aset (Unity)

Gunakan langkah-langkah dalam panduan ini untuk mengakses asset pack aplikasi dari kode C# Unity. Jika belum membuat app bundle dengan asset pack, lihat Membuat aplikasi untuk Unity sebelum melanjutkan.

Ringkasan

API Play Asset Delivery Unity menyediakan fungsi untuk meminta asset pack, mengelola download, dan mengakses aset. Fungsi yang digunakan di API bergantung pada bagaimana Anda membuat asset pack.

Jika Anda membuat asset pack menggunakan UI plugin, pilih Asset pack yang dikonfigurasi plugin.

Jika Anda membuat asset pack menggunakan API (atau UI plugin), pilih asset pack yang dikonfigurasi API.

Anda menerapkan API ini sesuai dengan jenis pengiriman asset pack yang ingin Anda akses. Langkah-langkah ini ditampilkan dalam diagram alir berikut.

Diagram alir asset pack untuk plugin

Gambar 1. Diagram alir untuk mengakses asset pack

Mengambil AssetBundles

Impor Play Asset Delivery dan panggil metode RetrieveAssetBundleAsync() untuk mengambil AssetBundle.

using Google.Play.AssetDelivery;

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

Pengiriman waktu penginstalan

Asset pack yang dikonfigurasi sebagai install-time akan segera tersedia saat aplikasi diluncurkan. Anda dapat menggunakan cara berikut untuk memuat scene dari 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]);

Pengiriman dimulai segera dan on demand

Bagian ini berlaku untuk asset pack fast-follow dan on-demand.

Memeriksa status

Setiap asset pack disimpan dalam folder terpisah dalam penyimpanan internal aplikasi. Gunakan metode isDownloaded() untuk menentukan apakah Asset pack sudah didownload.

Memantau download

Buat kueri objek PlayAssetBundleRequest untuk memantau status permintaan:

// 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.ShowCellularDataConfirmation dialog.
    default:
        break;
}

Hasil download berukuran besar

Ukuran asset pack yang lebih besar dari 150 MB dapat didownload secara otomatis, tetapi hanya jika terhubung ke Wi-Fi. Jika pengguna tidak berada dalam jaringan Wi-Fi, status PlayAssetBundleRequest akan ditetapkan ke AssetDeliveryStatus.WaitingForWifi dan download akan dijeda. Dalam hal ini, tunggu hingga perangkat tersambung ke Wi-Fi, melanjutkan download, atau meminta persetujuan pengguna untuk mendownload paket melalui koneksi seluler.

if(bundleRequest.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;
    }
}

Membatalkan permintaan (khusus on demand)

Jika Anda perlu membatalkan permintaan sebelum AssetBundle dimuat ke dalam memori, panggil metode AttemptCancel() pada PlayAssetBundleRequest:

// 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.
}

Meminta asset pack secara asinkron

Dalam sebagian besar kasus, Anda harus menggunakan Coroutine untuk meminta asset pack secara asinkron dan memantau progres, seperti yang ditunjukkan berikut ini:

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;

Untuk informasi selengkapnya tentang penanganan error, lihat daftar AssetDeliveryErrorCodes.

Metode Play Core API lainnya

Berikut ini adalah beberapa metode API tambahan yang mungkin ingin Anda gunakan pada aplikasi.

Memeriksa ukuran download

Memeriksa ukuran AssetBundle dengan melakukan panggilan asinkron ke Google Play dan menyetel metode callback saat operasi selesai:

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

Menghapus AssetBundles

Anda dapat menghapus AssetBundle yang dimulai segera dan on demand yang saat ini tidak dimuat ke dalam memori. Lakukan panggilan asinkron berikut dan setel metode callback saat selesai:

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

Langkah berikutnya

Uji pengiriman aset secara lokal dan dari Google Play.