Mengintegrasikan Asset Delivery (Unity)

Saat mengintegrasikan Asset Delivery, game Unity dapat mengakses paket aset menggunakan Addressables atau AssetBundles. Addressables adalah solusi pengiriman aset yang lebih baru dan direkomendasikan untuk game yang dibuat menggunakan Unity 2019.4 atau lebih tinggi, sementara AssetBundles memberikan dukungan paket aset di Unity 2017.4 dan 2018.4.

Addressables Unity

Game yang dibangun dengan Unity 2019.4 atau lebih tinggi harus menggunakan Addressables untuk pengiriman aset di Android. Unity menyediakan Play Asset Delivery (PAD) API untuk menangani paket aset Android menggunakan Addressables. Untuk informasi tentang penggunaan Addressables, lihat berikut ini:

Menggunakan file AssetBundle

Game yang dibangun dengan Unity 2017.4 dan 2018.4 dapat menggunakan file AssetBundle untuk pengiriman aset di Android. File AssetBundle Unity berisi aset serial yang dapat dimuat oleh mesin Unity saat aplikasi berjalan. File ini bersifat khusus untuk setiap platform (misalnya, dibuat untuk Android) dan dapat digunakan bersama paket aset. Biasanya, satu file AssetBundle dipaketkan menjadi satu paket aset, dengan paket yang menggunakan nama yang sama dengan AssetBundle. Jika Anda menginginkan fleksibilitas lebih tinggi dalam membuat paket aset, konfigurasikan paket aset menggunakan API.

Saat runtime, gunakan class Play Asset Delivery for Unity untuk mengambil AssetBundle yang dikemas dalam paket aset.

Prasyarat

  1. Download rilis terbaru Plugin Play Asset Delivery Unity dari paket Google untuk Unity.

  2. Membuat AssetBundles di Unity.

Mengonfigurasikan AssetBundles menggunakan UI

  1. Mengonfigurasikan setiap AssetBundle dalam sebuah paket aset:

    1. Pilih Google > Android App Bundle > Setelan Asset Delivery.
    2. Untuk memilih folder yang langsung berisi file AssetBundle, klik Tambahkan Folder.

  2. Untuk setiap paket, ubah Mode Pengiriman menjadi Saat Menginstal, Mulai Segera, atau On Demand. Atasi error atau dependensi, dan tutup jendela.

  3. Pilih Google > Buat Android App Bundle untuk membuat app bundle.

  4. (Opsional) Konfigurasikan app bundle Anda untuk mendukung berbagai format kompresi tekstur.

Mengonfigurasi paket aset menggunakan API

Anda dapat mengonfigurasi asset delivery melalui skrip editor yang dapat dijalankan sebagai bagian dari sistem build otomatis.

Gunakan class AssetPackConfig untuk menentukan aset yang akan disertakan dalam build Android App Bundle, serta mode pengiriman aset. Paket aset ini tidak perlu berisi 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);
}

Anda juga dapat menggunakan metode BuildBundle statis di class Bundletool untuk menghasilkan Android App Bundle dengan paket aset, mengingat BuildPlayerOptions dan AssetPackConfig.

Untuk tutorial terpandu, lihat Menggunakan Play Asset Delivery di Codelab game Unity.

Melakukan integrasi dengan Play Asset Delivery Unity API

Play Asset Delivery Unity API menyediakan fungsi untuk meminta paket aset, mengelola download, dan mengakses aset. Pastikan untuk Menambahkan plugin Unity terlebih dahulu ke project Anda.

Fungsi yang digunakan di API bergantung pada cara Anda membuat paket aset.

Jika Anda membuat paket aset menggunakan UI plugin, pilih Paket aset yang dikonfigurasi plugin.

Jika Anda membuat paket aset menggunakan API (atau UI plugin), pilih paket aset yang dikonfigurasi API.

API ini serupa, apa pun jenis pengiriman asset pack yang ingin Anda akses. Langkah-langkah ini ditampilkan dalam diagram alir berikut.

Diagram alur asset pack untuk API

Gambar 1. Diagram alir untuk mengakses asset pack

Mengambil paket aset

Impor library Play Asset Delivery dan panggil metode RetrieveAssetPackAsync() untuk mendownload paket aset jika versi terbaru paket ini belum tersedia di disk.

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

Pengiriman waktu penginstalan

Paket aset yang dikonfigurasi sebagai install-time akan segera tersedia saat aplikasi diluncurkan, tetapi Anda perlu memuat asetnya ke dalam memori. Lihat Memuat aset ke dalam memori.

Pengiriman dimulai segera dan on demand

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

Memeriksa status

Setiap paket aset disimpan dalam folder terpisah dalam penyimpanan internal aplikasi. Gunakan metode isDone() untuk menentukan apakah asset pack telah didownload dan tersedia, atau jika terjadi error.

Memantau download

Buat kueri objek PlayAssetPackRequest 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 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.ShowConfirmationDialog dialog.
    case AssetDeliveryStatus.RequiresUserConfirmation:
        // Asset pack retrieval paused until the user accepts the
        // PlayAssetDelivery.ShowConfirmationDialog 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;

Hasil download berukuran besar

Paket aset yang lebih besar dari 200 MB dapat otomatis didownload, tetapi hanya jika perangkat terhubung ke Wi-Fi. Jika pengguna tidak berada dalam jaringan Wi-Fi, status PlayAssetPackRequest 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.

Konfirmasi pengguna yang diperlukan

Jika paket memiliki status AssetDeliveryStatus.RequiresUserConfirmation, download tidak akan dilanjutkan hingga pengguna menyetujui dialog yang ditampilkan dengan PlayAssetDelivery.ShowConfirmationDialog(). Status ini dapat muncul jika aplikasi tidak dikenali oleh Play. Perhatikan bahwa memanggil PlayAssetDelivery.ShowConfirmationDialog() dalam hal ini akan menyebabkan aplikasi diupdate. Setelah pembaruan, minta aset lagi.

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

Membatalkan permintaan (khusus on demand)

Jika perlu membatalkan permintaan sebelum paket aset didownload, panggil metode AttemptCancel() pada objek PlayAssetPackRequest:

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

Memuat aset ke dalam memori

Setelah permintaan selesai, gunakan salah satu fungsi ini untuk memuat aset ke dalam memori:

Meminta paket aset secara asinkron

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

private IEnumerator LoadAssetPackCoroutine(string assetPackName) {

    PlayAssetPackRequest request =
        PlayAssetDelivery.RetrieveAssetPackAsync(assetPackName);

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

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

Untuk informasi selengkapnya tentang penanganan error, lihat daftar kode error.

Metode Play Core API lainnya

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

Mengambil beberapa asset pack

Untuk mengambil beberapa asset pack sekaligus, gunakan fungsi berikut:

// assetPackNames is an array of strings corresponding to asset packs.
PlayAssetPackBatchRequest batchRequest = PlayAssetDelivery.RetrieveAssetPackBatchAsync(<IListstring> assetPackNames);

Memantau status setiap permintaan dengan memeriksa Dictionary status:

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

Memeriksa ukuran download

Memeriksa ukuran asset pack 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 asset pack 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.