UnityWebRequest基础学习(post,get请求以及加载AssetBundle)

  1. Post请求:
    using UnityEngine;
    using UnityEngine.Networking;
    using System.Collections;

public class MyBehavior : MonoBehaviour
{
void Start()
{
StartCoroutine(Upload());
}

IEnumerator Upload()
{
    WWWForm form = new WWWForm();
    form.AddField("key", "value");
    UnityWebRequest request = UnityWebRequest.Post(url, form)
    yield return request.SendWebRequest();
    Debug.Log(request.error);
    Debug.Log(request.responseCode);
    Debug.Log(request.downloadHandler.text);
}

}

  1. Get请求
    IEnumerator Get()
    {
    UnityWebRequest request =UnityWebRequest.Get(url);
    yield return request.SendWebRequest();
    Debug.Log(request.error);
    Debug.Log(request.responseCode);
    Debug.Log(request.downloadHandler.text);
    }

  2. 加载AssetBundle
    第一种方式,将AssetBundle加载到缓存
    IEnumerator LoadABWeb()
    {
    UnityWebRequest request = UnityWebRequest.GetAssetBundle(path);
    yield return request.SendWebRequest();
    Debug.Log(request.error);
    AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);
    audio.clip = bundle.LoadAsset<AudioClip>("music");
    audio.Play();
    }
    第二种方式:加载AssetBundle并保存到本地

IEnumerator Test()
{
UnityWebRequest request =UnityWebRequest.Get(path);
yield return request.SendWebRequest();
CreatFile(path, request.downloadHandler.data,request.downloadHandler.data.Length);
AssetBundle ab=AssetBundle.LoadFromFile(path);
audio.clip = ab.LoadAsset<AudioClip>("music");
audio.Play();
}

void CreatFile(string path, byte[] file, int length)
{
Stream sw;
FileInfo File = new FileInfo(path);
if (!File.Exists)
{
sw = File.Create();
}
else
{
return;
}
sw.Write(file, 0, length);
sw.Close();
sw.Dispose();
}

推荐阅读更多精彩内容