Use as etapas deste guia para acessar os pacotes de recursos do app a partir do código do Unity C#. Se você ainda não criou um pacote de apps com pacotes de recursos, consulte Criar para Unity antes de continuar.
Geral
A API Unity Play Asset Delivery oferece a funcionalidade de solicitar pacotes de recursos, gerenciar downloads e acessar os recursos. As funções usadas na API dependem de como você criou os pacotes de recursos.
Se você criou pacotes de recursos usando a IU do plug-in, selecione Pacotes de recursos configurados pelo plug-in.
Se você criou pacotes de recursos usando a API (ou a IU do plug-in), selecione Pacotes de recursos configurados pela API.
Implemente a API de acordo com o tipo de entrega do pacote de recursos que você quer acessar. Essas etapas são mostradas no fluxograma a seguir.
Figura 1. Diagrama de fluxo para acessar pacotes de recursos
Recuperar AssetBundles
Importe a
biblioteca Play Asset Delivery
e chame o método
RetrieveAssetBundleAsync()
para recuperar um 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);
Entrega na instalação
Os pacotes de recursos configurados como install-time
estão imediatamente disponíveis na
inicialização do app. Você pode usar os seguintes meios para carregar uma cena do 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]);
Entrega rápida e sob demanda
Essas seções se aplicam aos pacotes de recursos fast-follow
e on-demand
.
Verificar status
Cada pacote de recursos é armazenado em uma pasta separada no armazenamento interno do app.
Use o método
isDownloaded()
para determinar se o download de um pacote de recursos já foi feito.
Monitorar o download
Consulte o objeto
PlayAssetBundleRequest
para monitorar o status da solicitação:
// 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; }
Downloads grandes
Os pacotes de recursos com mais de 150 MB podem ser transferidos por download automaticamente, mas somente por Wi-Fi. Se
o usuário não estiver usando Wi-Fi, o status PlayAssetBundleRequest
será definido como
AssetDeliveryStatus.WaitingForWifi
,
e o download será pausado. Nesse caso, aguarde até que o dispositivo se conecte
à rede Wi-Fi, retome o download ou peça ao usuário aprovação para fazer o download do
pacote em uma conexão celular.
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; } }
Cancelar uma solicitação (somente sob demanda)
Se você precisar cancelar a solicitação antes que os AssetBundles sejam carregados na
memória, chame o método
AttemptCancel()
no
objeto
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. }
Solicitar pacotes de recursos de forma assíncrona
Na maioria dos casos, é preciso usar Corrotinas para solicitar pacotes de recursos de forma assíncrona e monitorar o progresso, como mostrado a seguir:
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;
Para ver mais informações sobre como lidar com erros, consulte a lista de
AssetDeliveryErrorCodes
.
Outros métodos da API Play Core
Veja a seguir alguns métodos adicionais de API que podem ser usados no seu app.
Verificar o tamanho do download
Verifique o tamanho de um AssetBundle fazendo uma chamada assíncrona ao Google Play e definindo um método de callback para quando a operação for concluída:
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(); } }
Remover AssetBundles
É possível remover AssetBundles rápidos e sob demanda que não estão carregados atualmente na memória. Faça a chamada assíncrona a seguir e defina um método de callback para conclusão:
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. } };
Próxima etapa
Teste a entrega de recursos localmente e no Google Play.