WebAssetRequest.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. using UnityEngine;
  2. using UnityEngine.Networking;
  3. using Object = UnityEngine.Object;
  4. public class WebAssetRequest : AssetRequest
  5. {
  6. private UnityWebRequest _www;
  7. public override float progress
  8. {
  9. get
  10. {
  11. if (isDone) return 1;
  12. if (LoadState == AssetLoadState.Init) return 0;
  13. if (_www == null) return 1;
  14. return _www.downloadProgress;
  15. }
  16. }
  17. public override string error
  18. {
  19. get { return _www.error; }
  20. }
  21. internal override bool Update()
  22. {
  23. if (!base.Update())
  24. return false;
  25. if (LoadState == AssetLoadState.LoadAsset)
  26. {
  27. if (_www == null)
  28. {
  29. error = "www == null";
  30. return false;
  31. }
  32. if (!string.IsNullOrEmpty(_www.error))
  33. {
  34. error = _www.error;
  35. LoadState = AssetLoadState.Loaded;
  36. return false;
  37. }
  38. if (_www.isDone)
  39. {
  40. GetAsset();
  41. LoadState = AssetLoadState.Loaded;
  42. return false;
  43. }
  44. return true;
  45. }
  46. return true;
  47. }
  48. private void GetAsset()
  49. {
  50. if (assetType == typeof(Texture2D))
  51. asset = DownloadHandlerTexture.GetContent(_www);
  52. else if (assetType == typeof(AudioClip))
  53. asset = DownloadHandlerAudioClip.GetContent(_www);
  54. else if (assetType == typeof(TextAsset))
  55. text = _www.downloadHandler.text;
  56. else
  57. bytes = _www.downloadHandler.data;
  58. }
  59. internal override void Load()
  60. {
  61. if (assetType == typeof(AudioClip))
  62. {
  63. _www = UnityWebRequestMultimedia.GetAudioClip(name, AudioType.WAV);
  64. }
  65. else if (assetType == typeof(Texture2D))
  66. {
  67. _www = UnityWebRequestTexture.GetTexture(name);
  68. }
  69. else
  70. {
  71. _www = new UnityWebRequest(name);
  72. _www.downloadHandler = new DownloadHandlerBuffer();
  73. }
  74. _www.SendWebRequest();
  75. LoadState = AssetLoadState.LoadAsset;
  76. }
  77. internal override void Unload()
  78. {
  79. if (asset != null)
  80. {
  81. Object.Destroy(asset);
  82. asset = null;
  83. }
  84. if (_www != null)
  85. _www.Dispose();
  86. bytes = null;
  87. text = null;
  88. LoadState = AssetLoadState.Unload;
  89. }
  90. }