Skip to content

Instantly share code, notes, and snippets.

@sputn1ck
Last active March 19, 2020 22:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sputn1ck/6490da1ef7ea3979b93ecd162e7039e6 to your computer and use it in GitHub Desktop.
Save sputn1ck/6490da1ef7ea3979b93ecd162e7039e6 to your computer and use it in GitHub Desktop.
async webrequest
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
public class RequestTest : MonoBehaviour
{
public string url;
public int maxTries;
public bool requestTrigger;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (requestTrigger)
{
requestTrigger = false;
Request();
}
}
async void Request()
{
var req = new AwaitRequest(this, url,maxTries);
var res = await req.GetResult();
Debug.LogFormat("{0}, {1}, {2}", res.hasError, res.error, res.response);
}
}
public class AwaitRequest {
RequestResult result;
private int maxTries;
public AwaitRequest(MonoBehaviour mb, string url, int maxTries = 20) {
mb.StartCoroutine(GetRequest(url));
this.maxTries = maxTries;
}
public async Task<RequestResult> GetResult() {
// die tries sind da damit das programm zur not stoppt
int tries = 0;
while(result == null && tries < maxTries) {
tries++;
await Task.Delay(TimeSpan.FromSeconds(0.1));
}
if (tries >=maxTries){
return new RequestResult(){
hasError = true,
error = "exceeded max tries",
};
}
return result;
}
IEnumerator GetRequest(string uri)
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
{
// Request and wait for the desired page.
yield return webRequest.SendWebRequest();
if (webRequest.isNetworkError)
{
result = new RequestResult{
hasError = true,
error = webRequest.error
};
}
else
{
result = new RequestResult{
hasError = false,
response = webRequest.downloadHandler.text
};
}
}
}
}
public class RequestResult {
public string response;
public string error;
public bool hasError;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment