포스트

[Unity] SendWebRequest Async await 사용하기

해당 코드를 프로젝트 추가하면 UnityWebRequestAsyncOperation 를 Async 함수에서 await로 기다릴 수 있습니다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public struct UnityWebRequestAwaiter : INotifyCompletion  
{  
    private UnityWebRequestAsyncOperation asyncOp;  
    private Action continuation;  
  
    public UnityWebRequestAwaiter(UnityWebRequestAsyncOperation asyncOp)  
    {        this.asyncOp = asyncOp;  
        continuation = null;  
    }  
    public bool IsCompleted { get { return asyncOp.isDone; } }  
  
    public void GetResult() { }  
  
    public void OnCompleted(Action continuation)  
    {        this.continuation = continuation;  
        asyncOp.completed += OnRequestCompleted;  
    }  
    private void OnRequestCompleted(AsyncOperation obj)  
    {        continuation?.Invoke();  
    }}  
  
public static class ExtensionMethods  
{  
    public static UnityWebRequestAwaiter GetAwaiter(this UnityWebRequestAsyncOperation asyncOp)  
    {        return new UnityWebRequestAwaiter(asyncOp);  
    }}

사용 예시

1
2
3
var www = UnityWebRequest.Get(url);  
var ao = www.SendWebRequest(); // 응답이 올때까지 대기한다.  
await ao;
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.