using System; using System.Collections; using UnityEngine; using UnityEngine.Networking; namespace TriLib { public class AssetDownloader : MonoBehaviour { public bool HasStarted { get { return this._unityWebRequest != null; } } public bool IsDone { get { return this._unityWebRequest != null && this._unityWebRequest.isDone; } } public string Error { get { if (this.HasStarted) { return this._unityWebRequest.error ?? this._error; } return this._error; } } public float Progress { get { if (!this.HasStarted) { return 0f; } return this._unityWebRequest.downloadProgress; } } protected void Start() { if (!string.IsNullOrEmpty(this.AssetURI) && !string.IsNullOrEmpty(this.AssetExtension)) { this.DownloadAsset(this.AssetURI, this.AssetExtension, null, null, null, this.WrapperGameObject); } } protected void OnGUI() { if (!this.ShowProgress || !this.HasStarted || this.IsDone) { return; } if (this._centeredStyle == null) { this._centeredStyle = GUI.skin.GetStyle("Label"); this._centeredStyle.alignment = TextAnchor.UpperCenter; } Rect position = new Rect((float)Screen.width / 2f - 100f, (float)Screen.height / 2f - 25f, 200f, 50f); GUI.Label(position, string.Format("Downloaded {0:P2}", this.Progress), this._centeredStyle); } public bool DownloadAsset(string assetURI, string assetExtension, ObjectLoadedHandle onAssetLoaded = null, TexturePreLoadHandle onTexturePreLoad = null, AssetLoaderOptions options = null, GameObject wrapperGameObject = null) { if (this.HasStarted && !this.IsDone) { return false; } this.AssetURI = assetURI; this.AssetExtension = assetExtension; this.WrapperGameObject = wrapperGameObject; base.StartCoroutine(this.DoDownloadAsset(assetURI, assetExtension, onAssetLoaded, onTexturePreLoad, options, wrapperGameObject)); return true; } private IEnumerator DoDownloadAsset(string assetURI, string assetExtension, ObjectLoadedHandle onAssetLoaded, TexturePreLoadHandle onTexturePreLoad = null, AssetLoaderOptions options = null, GameObject wrapperGameObject = null) { this._unityWebRequest = UnityWebRequest.Get(assetURI); yield return this._unityWebRequest.Send(); if (string.IsNullOrEmpty(this._unityWebRequest.error)) { byte[] data = this._unityWebRequest.downloadHandler.data; using (AssetLoader assetLoader = new AssetLoader()) { assetLoader.LoadFromMemoryWithTextures(data, assetExtension, onAssetLoaded, out this._error, onTexturePreLoad, options, wrapperGameObject); } } this._unityWebRequest.Dispose(); this._unityWebRequest = null; yield break; } public string AssetURI; public string AssetExtension; public GameObject WrapperGameObject; public bool ShowProgress; private UnityWebRequest _unityWebRequest; private GUIStyle _centeredStyle; private string _error; } }