Web Request(WWW) Code Example
Unity 에서 Web Request 를 하는 방식의 일반적인 경우 2가지
코루틴, Task를 활용한 방식에 대한 예시코드이다.
Coroutine
private void Test1()
{
System.UriBuilder defaultUri = new System.UriBuilder(urlPath);
//defaultUri.Query +=
StartCoroutine(GetWebRequestText(defaultUri.Uri.ToString(),
(success, result) =>
{
if (success == false)
{
Debug.LogError($"[WWW] :<color=white>Error Url ::{defaultUri.Uri.ToString()}</color>\n <color=red>Result ::{result}</color>");
return;
}
Debug.Log($"[WWW] :<color=white> Url ::{defaultUri.Uri.ToString()}</color>\n <color=red>Result ::{result}</color>");
}));
}
private IEnumerator GetWebRequestText(string _url, System.Action<bool, string> _result)
{
Debug.Log($"[WWW] URL : <color=white>{_url}</color>");
using (UnityEngine.Networking.UnityWebRequest www = UnityEngine.Networking.UnityWebRequest.Get(_url))
{
yield return www.SendWebRequest();
string resultValue = string.Empty;
switch (www.result)
{
case UnityWebRequest.Result.Success:
resultValue = www.downloadHandler.text;
break;
case UnityWebRequest.Result.ConnectionError:
case UnityWebRequest.Result.DataProcessingError:
case UnityWebRequest.Result.ProtocolError:
resultValue = www.result.ToString();
break;
}
_result.Invoke((www.result == UnityWebRequest.Result.Success), resultValue);
}
}
Task
private async void Test2()
{
System.UriBuilder defaultUri = new System.UriBuilder(urlPath);
using var www = UnityWebRequest.Get(defaultUri.Uri.ToString());
var operation = www.SendWebRequest();
while (!operation.isDone)
await Task.Yield();
if (www.result == UnityWebRequest.Result.Success)
Debug.Log($"[WWW] :<color=white> Url ::{defaultUri.Uri.ToString()}</color>\n <color=red>Result ::{www.downloadHandler.text}</color>");
}
반응형
Unity WebReuqest : [링크]
★☆☆☆☆
반응형
댓글