AssetBundleSample.cs 6.3 KB

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