Skip to content

Instantly share code, notes, and snippets.

@restush
Last active June 9, 2023 22:29
Show Gist options
  • Save restush/c168df9c7b3d4b7b3c2c6f7c7c8ea81d to your computer and use it in GitHub Desktop.
Save restush/c168df9c7b3d4b7b3c2c6f7c7c8ea81d to your computer and use it in GitHub Desktop.
Unity Google Play Asset Delivery
using System;
using System.Collections;
using System.Linq;
using UnityEngine;
using UnityEngine.Android;
using UnityEngine.Networking;
using UnityEngine.UI;
public class Initializer : MonoBehaviour
{
[field: SerializeField] public LoadingCanvas _loadingCanvas { get; private set; }
[field: SerializeField] public Text progress { get; private set; }
private bool isDownloading = true;
private readonly string OnDemand = "CustomCharacters";
private bool isCheckingInternet = false;
private bool connectedToInternet = false;
private readonly string url = "https://www.example.com";
void CheckInternet()
{
if (isCheckingInternet)
return;
StartCoroutine(LoopCheckInternet());
}
void StopCheckInternet()
{
isCheckingInternet = false;
StopCoroutine(LoopCheckInternet());
StopCoroutine(GetRequest());
}
IEnumerator LoopCheckInternet()
{
isCheckingInternet = true;
while (isCheckingInternet)
{
yield return StartCoroutine(GetRequest());
yield return new WaitForSecondsRealtime(6);
}
}
IEnumerator GetRequest()
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
{
// Request and wait for the desired page.
yield return webRequest.SendWebRequest();
string[] pages = url.Split('/');
int page = pages.Length - 1;
switch (webRequest.result)
{
case UnityWebRequest.Result.ConnectionError:
connectedToInternet = false;
Debug.Log("Connection Error");
break;
case UnityWebRequest.Result.DataProcessingError:
connectedToInternet = false;
Debug.Log("Error: " + webRequest.error);
break;
case UnityWebRequest.Result.ProtocolError:
connectedToInternet = false;
Debug.Log("HTTP Error: " + webRequest.error);
break;
case UnityWebRequest.Result.Success:
connectedToInternet = true;
Debug.Log("Connection Success ");
break;
}
}
}
private IEnumerator CheckConnectedToInternet()
{
Debug.Log("Check internet");
yield return new WaitWhile(() => connectedToInternet == false);
Debug.Log("Connected to internet");
}
private IEnumerator Start()
{
CheckInternet();
isDownloading = true;
#if !UNITY_EDITOR
var state = AndroidAssetPacks.GetAssetPackStateAsync(new string[] { OnDemand });
yield return state;
Debug.Log("Status: " + state.states.FirstOrDefault().status);
if (state.states.FirstOrDefault().status != AndroidAssetPackStatus.Completed)
{
yield return StartCoroutine(CheckConnectedToInternet());
Debug.Log("Starting Download Asset");
AndroidAssetPacks.DownloadAssetPackAsync(new string[] { OnDemand }, DownloadStatus);
while (isDownloading)
{
if (!connectedToInternet)
Debug.Log("No internet connection");
else
Debug.Log("Downloading");
yield return new WaitForSeconds(2);
}
}
else if (state.states.FirstOrDefault().status == AndroidAssetPackStatus.Completed)
{
yield return StartCoroutine(FakeLoading());
}
yield return new WaitForEndOfFrame();
#elif UNITY_EDITOR
yield return StartCoroutine(FakeLoading());
#endif
_loadingCanvas.m_Progress_Text.text = ("100%");
_loadingCanvas.m_Progress_Image.fillAmount = (1);
_loadingCanvas.HideUI();
StopCheckInternet();
}
IEnumerator FakeLoading()
{
float timeOut = 3;
float timer = 0;
yield return StartCoroutine(CheckConnectedToInternet());
while (isDownloading)
{
timer += Time.deltaTime;
if (timer > timeOut)
isDownloading = false;
_loadingCanvas.m_Progress_Text.text = ($"{Math.Round((timer / timeOut) * 100)}%");
_loadingCanvas.m_Progress_Image.fillAmount = (timer / timeOut);
yield return null;
}
}
void DownloadStatus(AndroidAssetPackInfo info)
{
var _downloaded = info.bytesDownloaded * 1.0f / (1024 * 1024);
var _totalSize = info.size * 1.0f / (1024 * 1024);
string _progress = $" Downloading {info.name} {_downloaded}MB/ {_totalSize}MB \n" +
$" Progress: {(_downloaded / _totalSize) * 100}% \n" +
$" Status: {info.status} \n" +
$" Error: {info.error}";
_loadingCanvas.m_Progress_Text.text = ($"{Math.Round((_downloaded / _totalSize) * 100)}%");
_loadingCanvas.m_Progress_Image.fillAmount = (_downloaded / _totalSize);
if (progress != null)
progress.text = _progress;
switch (info.status)
{
case AndroidAssetPackStatus.Unknown:
break;
case AndroidAssetPackStatus.Pending:
break;
case AndroidAssetPackStatus.Downloading:
isDownloading = true;
break;
case AndroidAssetPackStatus.Transferring:
break;
case AndroidAssetPackStatus.Completed:
isDownloading = false;
break;
case AndroidAssetPackStatus.Failed:
OnError(true);
break;
case AndroidAssetPackStatus.Canceled:
OnError();
break;
case AndroidAssetPackStatus.WaitingForWifi:
OnError();
AndroidAssetPacks.RequestToUseMobileDataAsync(OnRequestToUseMobileDataComplete);
break;
case AndroidAssetPackStatus.NotInstalled:
break;
default:
break;
}
void OnError(bool retry = false)
{
_loadingCanvas.ShowQuitButton();
_loadingCanvas.ShowStatusErrorText(info.error.ToString());
if (retry)
{
Debug.Log("Download failed, will try download again");
StartCoroutine(TryingDownloading());
}
IEnumerator TryingDownloading()
{
yield return new WaitForSecondsRealtime(2);
Debug.Log("Try Download again");
StopCoroutine(Start());
StartCoroutine(Start());
}
}
void OnRequestToUseMobileDataComplete(AndroidAssetPackUseMobileDataRequestResult result)
{
if (!result.allowed)
{
Application.Quit();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment