UnityWebRequestでIEnumeratorを使いたくないので、いろいろ検索
■参照元
https://gist.github.com/krzys-h/9062552e33dd7bd7fe4a6c12db109a1a
名前空間ではまったのでメモ
UnityEngeineないと下記でコンパイルエラー
(asyncOp.completed += OnRequestCompleted;)
■Awaiterクラス作成とGetAwaiterによる拡張
using System;
using System.Runtime.CompilerServices;
using UnityEngine;
using UnityEngine.Networking;
public class UnityWebRequestAwaiter : INotifyCompletion
{
private UnityWebRequestAsyncOperation asyncOp;
private Action continuation;
public UnityWebRequestAwaiter(UnityWebRequestAsyncOperation asyncOp)
{
this.asyncOp = asyncOp;
asyncOp.completed += OnRequestCompleted;
}
public bool IsCompleted { get { return asyncOp.isDone; } }
public void GetResult() { }
public void OnCompleted(Action continuation)
{
this.continuation = continuation;
}
private void OnRequestCompleted(AsyncOperation obj)
{
continuation();
}
}
public static class ExtensionMethods
{
public static UnityWebRequestAwaiter GetAwaiter(this UnityWebRequestAsyncOperation asyncOp)
{
return new UnityWebRequestAwaiter(asyncOp);
}
}
■呼び出し方
public async Task abc()
{
WWWForm form = new WWWForm();
UnityWebRequest www = UnityWebRequest.Post("URL", form);
await www.SendWebRequest();
var response = www.downloadHandler.text;
}
public class TestData
{
public int aaaa;
public long bbbb;
public string cccc;
}
public async Task<TestData> Abc()
{
TestData ddd = new TestData();
WWWForm form = new WWWForm();
// URLはAPIを参照
UnityWebRequest www = UnityWebRequest.Post("URL", form);
await www.SendWebRequest();
var response = www.downloadHandler.text;
// レスポンスからdddにJsonから変換してデータを入れる。
return ddd;
}
■検索参考サイト
https://www.slideshare.net/UnityTechnologiesJapan/unite-tokyo-2018asyncawait
https://stackoverflow.com/questions/55489885/post-json-string-to-webapi-from-unity-c-httpclient-or-unitywebrequest
http://light11.hatenadiary.com/entry/2019/03/07/003356
https://qiita.com/mounntainn/items/3f39e0c57412c48508bf