TextureDownloadSample.cs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using BestHTTP;
  5. namespace BestHTTP.Examples
  6. {
  7. public sealed class TextureDownloadSample : MonoBehaviour
  8. {
  9. /// <summary>
  10. /// The URL of the server that will serve the image resources
  11. /// </summary>
  12. const string BaseURL = "https://besthttp.azurewebsites.net/Content/";
  13. #region Private Fields
  14. /// <summary>
  15. /// The downloadable images
  16. /// </summary>
  17. string[] Images = new string[9] { "One.png", "Two.png", "Three.png", "Four.png", "Five.png", "Six.png", "Seven.png", "Eight.png", "Nine.png" };
  18. /// <summary>
  19. /// The downloaded images will be stored as textures in this array
  20. /// </summary>
  21. Texture2D[] Textures = new Texture2D[9];
  22. #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
  23. /// <summary>
  24. /// True if all images are loaded from the local cache instead of the server
  25. /// </summary>
  26. bool allDownloadedFromLocalCache;
  27. #endif
  28. /// <summary>
  29. /// How many sent requests are finished
  30. /// </summary>
  31. int finishedCount;
  32. /// <summary>
  33. /// GUI scroll position
  34. /// </summary>
  35. Vector2 scrollPos;
  36. #endregion
  37. #region Unity Events
  38. void Awake()
  39. {
  40. // Set a well observable value
  41. // This is how many concurrent requests can be made to a server
  42. HTTPManager.MaxConnectionPerServer = 1;
  43. // Create placeholder textures
  44. for (int i = 0; i < Images.Length; ++i)
  45. Textures[i] = new Texture2D(100, 150);
  46. }
  47. void OnDestroy()
  48. {
  49. // Set back to its defualt value.
  50. HTTPManager.MaxConnectionPerServer = 4;
  51. }
  52. void OnGUI()
  53. {
  54. GUIHelper.DrawArea(GUIHelper.ClientArea, true, () =>
  55. {
  56. scrollPos = GUILayout.BeginScrollView(scrollPos);
  57. // Draw out the textures
  58. GUILayout.SelectionGrid(0, Textures, 3);
  59. #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
  60. if (finishedCount == Images.Length && allDownloadedFromLocalCache)
  61. GUIHelper.DrawCenteredText("All images loaded from the local cache!");
  62. #endif
  63. GUILayout.FlexibleSpace();
  64. GUILayout.BeginHorizontal();
  65. GUILayout.Label("Max Connection/Server: ", GUILayout.Width(150));
  66. GUILayout.Label(HTTPManager.MaxConnectionPerServer.ToString(), GUILayout.Width(20));
  67. HTTPManager.MaxConnectionPerServer = (byte)GUILayout.HorizontalSlider(HTTPManager.MaxConnectionPerServer, 1, 10);
  68. GUILayout.EndHorizontal();
  69. if (GUILayout.Button("Start Download"))
  70. DownloadImages();
  71. GUILayout.EndScrollView();
  72. });
  73. }
  74. #endregion
  75. #region Private Helper Functions
  76. void DownloadImages()
  77. {
  78. // Set these metadatas to its initial values
  79. #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
  80. allDownloadedFromLocalCache = true;
  81. #endif
  82. finishedCount = 0;
  83. for (int i = 0; i < Images.Length; ++i)
  84. {
  85. // Set a blank placeholder texture, overriding previously downloaded texture
  86. Textures[i] = new Texture2D(100, 150);
  87. // Construct the request
  88. var request = new HTTPRequest(new Uri(BaseURL + Images[i]), ImageDownloaded);
  89. // Set the Tag property, we can use it as a general storage bound to the request
  90. request.Tag = Textures[i];
  91. // Send out the request
  92. request.Send();
  93. }
  94. }
  95. /// <summary>
  96. /// Callback function of the image download http requests
  97. /// </summary>
  98. void ImageDownloaded(HTTPRequest req, HTTPResponse resp)
  99. {
  100. // Increase the finished count regardless of the state of our request
  101. finishedCount++;
  102. switch (req.State)
  103. {
  104. // The request finished without any problem.
  105. case HTTPRequestStates.Finished:
  106. if (resp.IsSuccess)
  107. {
  108. // Get the Texture from the Tag property
  109. Texture2D tex = req.Tag as Texture2D;
  110. // Load the texture
  111. tex.LoadImage(resp.Data);
  112. #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
  113. // Update the cache-info variable
  114. allDownloadedFromLocalCache = allDownloadedFromLocalCache && resp.IsFromCache;
  115. #endif
  116. }
  117. else
  118. {
  119. Debug.LogWarning(string.Format("Request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
  120. resp.StatusCode,
  121. resp.Message,
  122. resp.DataAsText));
  123. }
  124. break;
  125. // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
  126. case HTTPRequestStates.Error:
  127. Debug.LogError("Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception"));
  128. break;
  129. // The request aborted, initiated by the user.
  130. case HTTPRequestStates.Aborted:
  131. Debug.LogWarning("Request Aborted!");
  132. break;
  133. // Connecting to the server is timed out.
  134. case HTTPRequestStates.ConnectionTimedOut:
  135. Debug.LogError("Connection Timed Out!");
  136. break;
  137. // The request didn't finished in the given time.
  138. case HTTPRequestStates.TimedOut:
  139. Debug.LogError("Processing the request Timed Out!");
  140. break;
  141. }
  142. }
  143. #endregion
  144. }
  145. }