Unity3D iOS 平台放弃 WWW 采用 UnityWebRequest

https://blog.****.net/ykr168age/article/details/68923331

使用的是 Unity 5.3.4, WWW 再 iOS 上加载资源出现卡死的问题:加载到一定程度卡死,重启APP后又可以跑过去,有些机型上甚至出现下载资源过不去的情况。解决方案,使用 UnityWebRequest 代替 WWW。当然 UnityWebRequest 次版本的 Dispose 有问题,更新到最新版就没问题了。

 

 

UnityWebRequest 架构

 

UnityWebRequest  由三个元素组成。

◾UploadHandler        处理数据  将数据发送到服务器 的对象

◾DownloadHandler    从服务器接收数据 的对象

◾UnityWebRequest      负责 HTTP 通信流量控制来管理上面两个对象的对象。

来说明这些对象之间的关系,如下所示。

Unity3D iOS 平台放弃 WWW 采用 UnityWebRequest

 

 

 

基本用法

 

比较UnityWebRequest 和 WWW 类的基本用法。

GET

www 通过 url 的写法:

 

 

 
  1. using UnityEngine;

  2. using System.Collections;

  3.  
  4. class MyBehaviour : public MonoBehaviour {

  5. void Start() {

  6. StartCoroutine(GetText());

  7. }

  8.  
  9. IEnumerator GetText() {

  10. WWW request = new WWW("http://example.com");

  11.  
  12. yield return request;

  13.  
  14. if (! string .IsNullOrEmpty(request.error)) {

  15. Debug.Log(request.error)

  16. } else {

  17. //

  18. if (request.responseHeaders.ContainsKey("STATUS") &&

  19. request.responseHeaders["STATUS"] == 200) {

  20. //

  21. string text = request.text;

  22.  
  23. //

  24. byte [] results = request.bytes;

  25. }

  26. }

  27. }

  28. }

 

 

 

 

UnityWebRequest的书写方式

 

 

 
  1. using UnityEngine;

  2. using System.Collections;

  3. using UnityEngine.Experimental.Networking;

  4. //

  5. // using UnityEngine.Networking;

  6.  
  7. class MyBehaviour : public MonoBehaviour {

  8. void Start() {

  9. StartCoroutine(GetText());

  10. }

  11.  
  12. IEnumerator GetText() {

  13. UnityWebRequest request = UnityWebRequest.Get("http://example.com");

  14. //

  15. // UnityWebRequest request = new UnityWebRequest("http://example.com");

  16. //

  17. // request.method = UnityWebRequest.kHttpVerbGET;

  18.  
  19. //

  20. yield return request.Send();

  21.  
  22. //

  23. if (request.isError) {

  24. Debug.Log(request.error);

  25. } else {

  26. if (request.responseCode == 200) {

  27. //

  28. string text = request.downloadHandler.text;

  29.  
  30. //

  31. byte [] results = request.downloadHandler.data;

  32. }

  33. }

  34. }

  35. }