Download Video from URL Array List with UnityWebRequest

Dear Unity Members,

I use UnityWebrequest function for downloading video and picture. And it works good.

For example: I have two URLs on my array list(VideoURLs). And I have video1 and video2 URLs in this array list. OK! This codes download all videos perfectly! But downloaded videos names are always video2(the last variable of array list)… This code download video1(with named video2), and video2 is overwrited on video1(because video1 name was video2). More description is below…

I have added my URLs to here:

public string[] VideoURLs;

And when I click a button running this void Download() function:

public void Download()
    {
        int URLCount = VideoURLs.Length;

        for (counter = 0; counter < URLCount; counter++)
        {
            URLVideo = VideoURLs[counter];
            StartCoroutine(DownloadVideo());
        }
    }

And the IEnumerator DownloadVideo() coroutine function is this:

public IEnumerator DownloadVideo()
    {
       UnityWebRequest wwwVideo = UnityWebRequest.Get(URLVideo);
        yield return wwwVideo.SendWebRequest(); //After this line coroutine will not continue and go back to  Download() Function. Why?
  
        if (wwwVideo.isNetworkError || wwwVideo.isHttpError)
        {
        Debug.Log(wwwVideo.error);
        }
    else
        {
            File.WriteAllBytes(Application.persistentDataPath + "Video"+ counter + ".mp4" , wwwVideo.downloadHandler.data);
//Writing videos... But its writing only last array counter name... And all videos are writing overwriting with same name(with last counter value)
        }   
    }

Thank you all for help and assistance…

1 Like

Dear Unity Members,

HERE IS THE SOLUTION:
My Download() function is a standart void function. But DownloadVideo() function type is IEnumerator. So; While the IEnumerator DownloadVideo() function is still running, void Download() function is not waiting for end of IEnumerator DownloadVideo() function.

When I understand that, I have changed the void Download() to IEnumerator Download(). And I called the IEnumerator DownloadVideo() function with yield return StartCoroutine(DownloadVideo()); // this line mean is: wait for DownloadVideo() function is finished!

The last version of void Download() function is here: (" With new type: IEnumerator Download()" )

public IEnumerator Download()
    {
        int URLCount = VideoURLs.Length;
        for (counter = 0; counter < URLCount; counter++)
        {
            URLVideo = VideoURLs[counter];
          yield return StartCoroutine(DownloadVideo());
          // this "yield return" mean is: wait for DownloadVideo() function is finished! I mean, "for loop" is froozen now...
        }
    }

Thank you and best wishes!

3 Likes