Now I'm using HttpWebRequest, but it takes too long to check the
availability of my file
That's because you are not doing that in another Thread
so it will like block the main Thread until the request is done. Using HttpWebRequest
requires threading and a way to notify the main thread when you are done.
You should use Unity's WWW
or UnityWebRequest
to make that request in a coroutine. These two API will make the question with Thread in the background. You just wait for it to finish with a coroutine. You can organize multiple requests with the help of Action
.
A simple re-usable download function that returns true on success:
IEnumerator getRequest(string uri, Action<bool> success)
{
UnityWebRequest uwr = UnityWebRequest.Get(uri);
yield return uwr.SendWebRequest();
//Check if there is an error
if (uwr.isError || !String.IsNullOrEmpty(uwr.error))
{
success(false);
}
else
{
success(true);
//Store downloaded data to the global variable
downloadedData = uwr.downloadHandler.data;
}
}
To make requests in order(3 requests):
IEnumerator downloadMultipleFile()
{
bool success = false;
//Download first file
yield return getRequest(url1, (status) => { success = status; });
//Check if download was successful
if (success)
{
Debug.Log("File downloaded from the first url");
//Use downloadedData here
//Exit
yield break;
}
Debug.Log("Error downloading from first url");
//Download second file
yield return getRequest(url2, (status) => { success = status; });
//Check if download was successful
if (success)
{
Debug.Log("File downloaded from the second url");
//Use downloadedData here
//Exit
yield break;
}
Debug.Log("Error downloading from second url");
//Download third file
yield return getRequest(url3, (status) => { success = status; });
//Check if download was successful
if (success)
{
Debug.Log("File downloaded from the second url");
//Use downloadedData here
//Exit
yield break;
}
Debug.Log("Error downloading from third url");
}
Usage:
string url1 = "https://images.pexels.com/photos/38265/flower-blossom-bloom-winter-38265.jpeg";
string url2 = "https://images.pexels.com/photos/404313/pexels-photo-404313.jpeg";
string url3 = "https://images.pexels.com/photos/65891/prairie-dog-rodent-animals-cynomys-65891.jpeg";
byte[] downloadedData;
void Start()
{
StartCoroutine(downloadMultipleFile());
}