AssetBundleSample.cs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6. using BestHTTP;
  7. namespace BestHTTP.Examples.HTTP
  8. {
  9. public sealed class AssetBundleSample : BestHTTP.Examples.Helpers.SampleBase
  10. {
  11. #pragma warning disable 0649
  12. [Tooltip("The url of the resource to download")]
  13. [SerializeField]
  14. private string _path = "/AssetBundles/WebGL/demobundle.assetbundle";
  15. [SerializeField]
  16. private string _assetnameInBundle = "9443182_orig";
  17. [SerializeField]
  18. private Text _statusText;
  19. [SerializeField]
  20. private RawImage _rawImage;
  21. [SerializeField]
  22. private Button _downloadButton;
  23. #pragma warning restore
  24. #region Private Fields
  25. /// <summary>
  26. /// Reference to the request to be able to call Abort on it.
  27. /// </summary>
  28. HTTPRequest request;
  29. /// <summary>
  30. /// The downloaded and cached AssetBundle
  31. /// </summary>
  32. AssetBundle cachedBundle;
  33. #endregion
  34. #region Unity Events
  35. protected override void Start()
  36. {
  37. base.Start();
  38. this._statusText.text = "Waiting for user interaction";
  39. }
  40. void OnDestroy()
  41. {
  42. if (this.request != null)
  43. this.request.Abort();
  44. this.request = null;
  45. UnloadBundle();
  46. }
  47. /// <summary>
  48. /// GUI button callback
  49. /// </summary>
  50. public void OnStartDownloadButton()
  51. {
  52. this._downloadButton.enabled = false;
  53. UnloadBundle();
  54. StartCoroutine(DownloadAssetBundle());
  55. }
  56. #endregion
  57. #region Private Helper Functions
  58. IEnumerator DownloadAssetBundle()
  59. {
  60. // Create and send our request
  61. request = new HTTPRequest(new Uri(this.sampleSelector.BaseURL + this._path)).Send();
  62. this._statusText.text = "Download started";
  63. // Wait while it's finishes and add some fancy dots to display something while the user waits for it.
  64. // A simple "yield return StartCoroutine(request);" would do the job too.
  65. while (request.State < HTTPRequestStates.Finished)
  66. {
  67. yield return new WaitForSeconds(0.1f);
  68. this._statusText.text += ".";
  69. }
  70. // Check the outcome of our request.
  71. switch (request.State)
  72. {
  73. // The request finished without any problem.
  74. case HTTPRequestStates.Finished:
  75. if (request.Response.IsSuccess)
  76. {
  77. #if !BESTHTTP_DISABLE_CACHING
  78. if (request.Response.IsFromCache)
  79. this._statusText.text = "Loaded from local cache!";
  80. else
  81. this._statusText.text = "Downloaded!";
  82. #else
  83. this._statusText.text = "Downloaded!";
  84. #endif
  85. // Start creating the downloaded asset bundle
  86. AssetBundleCreateRequest async =
  87. #if UNITY_5_3_OR_NEWER
  88. AssetBundle.LoadFromMemoryAsync(request.Response.Data);
  89. #else
  90. AssetBundle.CreateFromMemory(request.Response.Data);
  91. #endif
  92. // wait for it
  93. yield return async;
  94. BestHTTP.PlatformSupport.Memory.BufferPool.Release(request.Response.Data);
  95. // And process the bundle
  96. yield return StartCoroutine(ProcessAssetBundle(async.assetBundle));
  97. }
  98. else
  99. {
  100. this._statusText.text = string.Format("Request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
  101. request.Response.StatusCode,
  102. request.Response.Message,
  103. request.Response.DataAsText);
  104. Debug.LogWarning(this._statusText.text);
  105. }
  106. break;
  107. // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
  108. case HTTPRequestStates.Error:
  109. this._statusText.text = "Request Finished with Error! " + (request.Exception != null ? (request.Exception.Message + "\n" + request.Exception.StackTrace) : "No Exception");
  110. Debug.LogError(this._statusText.text);
  111. break;
  112. // The request aborted, initiated by the user.
  113. case HTTPRequestStates.Aborted:
  114. this._statusText.text = "Request Aborted!";
  115. Debug.LogWarning(this._statusText.text);
  116. break;
  117. // Connecting to the server is timed out.
  118. case HTTPRequestStates.ConnectionTimedOut:
  119. this._statusText.text = "Connection Timed Out!";
  120. Debug.LogError(this._statusText.text);
  121. break;
  122. // The request didn't finished in the given time.
  123. case HTTPRequestStates.TimedOut:
  124. this._statusText.text = "Processing the request Timed Out!";
  125. Debug.LogError(this._statusText.text);
  126. break;
  127. }
  128. this._downloadButton.enabled = true;
  129. }
  130. /// <summary>
  131. /// In this function we can do whatever we want with the freshly downloaded bundle.
  132. /// In this example we will cache it for later use, and we will load a texture from it.
  133. /// </summary>
  134. IEnumerator ProcessAssetBundle(AssetBundle bundle)
  135. {
  136. if (bundle == null)
  137. yield break;
  138. // Save the bundle for future use
  139. cachedBundle = bundle;
  140. // Start loading the asset from the bundle
  141. var asyncAsset =
  142. #if UNITY_5_1 || UNITY_5_2 || UNITY_5_3_OR_NEWER
  143. cachedBundle.LoadAssetAsync(this._assetnameInBundle, typeof(Texture2D));
  144. #else
  145. cachedBundle.LoadAsync(this._assetnameInBundle, typeof(Texture2D));
  146. #endif
  147. // wait til load
  148. yield return asyncAsset;
  149. // get the texture
  150. this._rawImage.texture = asyncAsset.asset as Texture2D;
  151. }
  152. void UnloadBundle()
  153. {
  154. this._rawImage.texture = null;
  155. if (cachedBundle != null)
  156. {
  157. cachedBundle.Unload(true);
  158. cachedBundle = null;
  159. }
  160. }
  161. #endregion
  162. }
  163. }