Save data async (and wait for it) from a coroutine
Hello all, Hopefully someone can help me. I was previously using async functions to get/post data to our web servers which worked great, however the verson of Unity we are using (2018.1) does not support TLS 1.2. A beta version does, however we then run into a problem that Unity IAP is broken for that version, so i'm stuck having to revert lots of code calls back to use coroutines and UnityWebRequest functions.
At game start, we download various bits of data, assetbundles etc. I can get them downloading fine with UnityWebRequest in a coroutine, however I then need to be able to save this data to disk, async and wait for this to complete.
How can I do this from a Coroutine? Alternatively, i'd much prefer to use HttpWebRequest functions, as theyre async and I can control and return from those much better, so how could we implement a version of TLS 1.2 in our current Unity version?
Thanks for help in advance, Jack
Answer by Legend_Bacon · May 30, 2018 at 04:14 PM
Hello there,
I'm not too sure about the specifics of your problem, but I hope this can help you. This is how I get a translation text from a database in an asynchronous manner.
• This is to call the Coroutine:
StartCoroutine(GetTranslationCoroutine(value =>
{
// The code in here only runs once the Coroutine is has returned something////////////
if (value.Key)
// Value seems to be valid, do something with 'value.Value'
else
UnityEngine.Debug.LogError("Could not retrieve translation for: " + translationKey);
/////////////////////////////////////////////////////////////////
}, translationKey));
• And this is the Coroutine itself:
public IEnumerator GetTranslationCoroutine(Action<KeyValuePair<bool, string>> value, string translationKey)
{
WWWForm form = new WWWForm();
form.AddField("post_translation_key", translationKey);
WWW www = new WWW("the url");
while (!www.isDone)
{
// Processing...
yield return null;
}
if (www.bytesDownloaded > 0)
{
//Here, perform checks to see if the returned data is valid
if(!string.IsNullOrEmpty(www.text))
{
//This returns a value to the callback. Note that the code after this line still gets executed.
value(new KeyValuePair<bool, string>(true, www.text));
}
else
{
value(new KeyValuePair<bool, string>(false, "some error message: " + www.error));
}
}
else
{
value(new KeyValuePair<bool, string>(false, "some error message: " + www.error));
}
yield return null;
}
Hopefully this can give you a lead.
Cheers,
~LegendBacon
Is that async? I was under the impression coroutines are not async.
Your answer
Follow this Question
Related Questions
How call async task in Unity 4 Answers
Load Scene in Background and Load When a Button is Clicked 0 Answers
Is true async scene loading possible? 0 Answers
Unity coroutine movement over time is not consistent/accurate? 1 Answer
Power up not working 0 Answers