[计算机] UnityWebRequest常用方法及简单使用

查看:637 |回复:1 | 2021-9-3 09:41:30

您需要 登录 才可以下载或查看,没有账号?注册

x
本帖最后由 MrTang1988 于 2021-9-3 09:46 编辑


简单分装了UnityWebRequest常用方法,接收文件或二进制数据、接收Texture、读取AssetBundle资源,并进行处理、Untiy To Web发送消息,并进行返回数据参数进行处理。仅供参考~~~
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Networking;

  5. public class UnityWebRequestTool : MonoBehaviour {
  6.     public static UnityWebRequestTool Instance;
  7.     public delegate void LoadAessetEndDelegate<T>(T AB);
  8.     private string _assetBundlePath;
  9.     private string _assetBundleName;
  10.     private Dictionary<string, string> WWWFormDictionary;
  11.     // Use this for initialization
  12.     void Awake() {
  13.         Instance = this;
  14.         WWWFormDictionary = new Dictionary<string, string>();
  15.     }
  16.     /// <summary>
  17.     /// Untiy To Web发送消息,并返回数据参数进行处理
  18.     /// </summary>
  19.     /// <param name="form"></param>
  20.     /// <param name="_action"></param>
  21.     public void UnityToWebRequestPost(Dictionary<string, string> form, LoadAessetEndDelegate<string> _action)
  22.     {
  23.         WWWFormDictionary.Clear();
  24.         WWWFormDictionary = form;
  25.         StartCoroutine(UnityToWebPost(_action));
  26.     }
  27.     /// <summary>
  28.     ///  向服务端发送form数据(以需求进行拓展)
  29.     /// </summary>
  30.     /// <returns></returns>
  31.     IEnumerator UnityToWebPost(LoadAessetEndDelegate<string> _action)
  32.     {      
  33.         WWWForm form = new WWWForm();     
  34.         foreach(string key in WWWFormDictionary.Keys)
  35.         {
  36.             form.AddField(key, WWWFormDictionary[key]);
  37.         }
  38.         //Path 根据需求进行修改
  39.         UnityWebRequest webRequest = UnityWebRequest.Post("http://www.baidu.com", form);
  40.         yield return webRequest.SendWebRequest();
  41.         //异常处理,很多博文用了error!=null这是错误的,请看下文其他属性部分
  42.         if (webRequest.isHttpError || webRequest.isNetworkError)
  43.             Debug.Log(webRequest.error);
  44.         else
  45.         {
  46.             Debug.Log(webRequest.downloadHandler.text);

  47.             if (_action != null)
  48.             {
  49.                 _action(webRequest.downloadHandler.text);
  50.             }
  51.         }
  52.     }
  53.     /// <summary>
  54.     /// 接收文件或二进制数据
  55.     /// </summary>
  56.     /// <param name="_path"></param>
  57.     /// <param name="_assetName"></param>
  58.     /// <param name="_action"></param>
  59.     public void LoadAsset(string _path, string _assetName ,LoadAessetEndDelegate<DownloadHandler> _byte=null)
  60.     {
  61.         _assetBundlePath = _path;
  62.         _assetBundleName = _assetName;
  63.         StartCoroutine(GetText(_byte));
  64.     }
  65.     /// <summary>
  66.     /// 接收文件或二进制数据
  67.     /// </summary>
  68.     /// <returns></returns>
  69.     IEnumerator GetText(LoadAessetEndDelegate<DownloadHandler> _action)
  70.     {
  71.         UnityWebRequest www = UnityWebRequest.Get(_assetBundlePath+ _assetBundleName);
  72.         yield return www.SendWebRequest();

  73.         if (www.isNetworkError || www.isHttpError)
  74.         {
  75.             Debug.Log(www.error);
  76.         }
  77.         else
  78.         {
  79.             // 接收文本数据,并打印到日志中
  80.             Debug.Log(www.downloadHandler.text);
  81.             DownloadHandler down = www.downloadHandler;
  82.             // 接收二进制数据
  83.             byte[] results = www.downloadHandler.data;
  84.             if (_action != null)
  85.             {
  86.                 _action(down);
  87.             }
  88.         }
  89.     }
  90.     /// <summary>
  91.     /// 接收Texture
  92.     /// </summary>
  93.     /// <param name="_path"></param>
  94.     /// <param name="_assetName"></param>
  95.     /// <param name="_texture"></param>
  96.     public void LoadAsset(string _path, string _assetName, LoadAessetEndDelegate<Texture> _texture=null)
  97.     {
  98.         _assetBundlePath = _path;
  99.         _assetBundleName = _assetName;
  100.         StartCoroutine(GetTexture(_texture));
  101.     }
  102.     /// <summary>
  103.     ///  接收Texture
  104.     /// </summary>
  105.     /// <returns></returns>
  106.     IEnumerator GetTexture(LoadAessetEndDelegate<Texture> _action)
  107.     {
  108.         UnityWebRequest www = UnityWebRequestTexture.GetTexture(_assetBundlePath + _assetBundleName);
  109.         yield return www.SendWebRequest();

  110.         if (www.isNetworkError || www.isHttpError)
  111.         {
  112.             Debug.Log(www.error);
  113.         }
  114.         else
  115.         {
  116.             //获取并创建Texture
  117.             //Texture myTexture = ((DownloadHandlerTexture)www.downloadHandler).texture;
  118.             Texture myTexture = DownloadHandlerTexture.GetContent(www);
  119.             if (_action != null)
  120.             {
  121.                 _action(myTexture);
  122.             }
  123.         }
  124.     }
  125.     /// <summary>
  126.     /// 读取AssetBundle资源,并进行处理
  127.     /// </summary>
  128.     /// <param name="_path"></param>
  129.     /// <param name="_assetName"></param>
  130.     /// <param name="_action"></param>
  131.     public void LoadAssetBundle(string _path,string _assetName, AssetType _assetPathType, LoadAessetEndDelegate<AssetBundle> _action=null)
  132.     {
  133.         _assetBundlePath = _path;
  134.         _assetBundleName = _assetName;
  135.         if(_assetPathType== AssetType.Local)
  136.         {
  137.             LoadFromFile(_action);
  138.         }
  139.         else if (_assetPathType == AssetType.Server)
  140.         {
  141.             StartCoroutine(GetAssetBundle(_action));
  142.         }            
  143.    }   
  144.     /// <summary>
  145.     /// 下载assetbundle资源
  146.     /// </summary>
  147.     /// <returns></returns>
  148.     IEnumerator GetAssetBundle(LoadAessetEndDelegate<AssetBundle> _action)
  149.     {
  150.         UnityWebRequest www = UnityWebRequestAssetBundle.GetAssetBundle(_assetBundlePath + _assetBundleName);
  151.         yield return www.SendWebRequest();
  152.         if (www.isNetworkError || www.isHttpError)
  153.         {
  154.             Debug.Log(www.error);
  155.         }
  156.         else
  157.         {
  158.             AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(www);
  159.             if (_action != null)
  160.             {              
  161.                 _action(bundle);
  162.             }
  163.         }
  164.     }
  165.     /// <summary>
  166.     ///  读取本地资源
  167.     /// </summary>
  168.     /// <param name="path"></param>
  169.     /// <param name="assetName"></param>
  170.     /// <param name="_action"></param>
  171.     private void LoadFromFile( LoadAessetEndDelegate<AssetBundle> _action = null)
  172.     {
  173.         //传入这个AB包存在本地的路径加载本地资源
  174.         AssetBundle ab = AssetBundle.LoadFromFile(_assetBundlePath + _assetBundleName);
  175.         if (_action != null)
  176.         {
  177.             _action(ab);
  178.         }
  179.     }
  180. }
  181. public enum AssetType
  182. {
  183.     Server, Local, Text,Texture,AssetBundle
  184. }
点击此处复制文本

  1. //测试类代码:工程中需有相应的测试元素(测试获取服务器资源、本地资源)参考
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.Networking;
  6. public class UnityWebRequestToolTest : MonoBehaviour {  
  7.     /// <summary>
  8.     /// 测试
  9.     /// </summary>
  10.     public void ClickButton(string _type)
  11.     {
  12.         switch (_type)
  13.         {
  14.             case "Text":
  15.                 GetText();
  16.                 break;
  17.             case "Texture":
  18.                 GetTexture();
  19.                 break;
  20.             case "AssetBundle":
  21.                 GetAesset();
  22.                 break;
  23.         }
  24.     }
  25.     private void GetText()
  26.     {
  27.         UnityWebRequestTool.Instance.LoadAsset("http://localhost:8080/FBX/", "Text.txt", GetTextAesst);
  28.     }
  29.     private void GetTextAesst(DownloadHandler handler)
  30.     {
  31.         Debug.Log(handler.text);
  32.     }
  33.     public Material Material;
  34.     private void GetTexture()
  35.     {
  36.         //UnityWebRequesTool.Instance.LoadAsset("http://localhost:8080/FBX/", "beijing.png", GetTextureAesst);
  37.         UnityWebRequestTool.Instance.LoadAsset(Application.dataPath + "/StreamingAssets/BuildAssetBundle/Window/", "beijing.png", GetTextureAesst);      
  38.     }
  39.     private void GetTextureAesst(Texture Texture)
  40.     {      
  41.         Material.SetTexture("_MainTex", Texture);
  42.     }
  43.     private void GetAesset()
  44.     {
  45.         //   UnityWebRequesTool.Instance.LoadAssetBundle("http://localhost:8080/FBX/", "mainasset",AssetType.Server , GetAessetBundle);
  46.         UnityWebRequestTool.Instance.LoadAssetBundle(Application.dataPath + "/StreamingAssets/BuildAssetBundle/Window/", "mainasset", AssetType.Local, GetAessetBundle);
  47.     }
  48.     private void GetAessetBundle(AssetBundle ab)
  49.     {
  50.         GameObject go = ab.LoadAsset<GameObject>("image.prefab");
  51.         GameObject gos = Instantiate(go, Vector3.zero, Quaternion.identity) as GameObject;
  52.         gos.transform.SetParent(GameObject.Find("Canvas").transform.GetComponent<RectTransform>());
  53.         gos.transform.GetComponent<RectTransform>().localPosition = Vector2.zero;
  54.         gos.transform.GetComponent<RectTransform>().anchoredPosition = Vector2.zero;
  55.         ab.Unload(false);
  56.     }
  57. }
点击此处复制文本


评分

参与人数 1活跃度 +16 展开 理由
愚不是渔 + 16 【点赞】这很有大网气质!

查看全部评分

2021-9-3 09:41:30  
 赞 赞 2

使用道具 登录

1个回答,把该问题分享到群,邀请大神一起回答。
2#
回复 收起回复
2023-3-1 12:09:16   回复
 赞 赞 1

使用道具 登录

CG 游戏行业专业问题

程序逻辑文章算法
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表