AssetBundleSample.cs 6.4 KB

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