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.

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 paket aset 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.ShowConfirmationDialog dialog.
    case AssetDeliveryStatus.RequiresUserConfirmation:
        // Asset pack retrieval paused until the user accepts the
        // PlayAssetDelivery.ShowConfirmationDialog dialog.
    default:
        break;
}

Hasil download berukuran besar

Paket aset yang lebih besar dari 200 MB dapat didownload secara otomatis, tetapi hanya melalui 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.

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 Anda perlu membatalkan permintaan sebelum AssetBundles dimuat ke dalam memori, panggil metode AttemptCancel() pada objek 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 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 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.