Search code examples
c#unity-game-engineunity-networking

UnityWebRequest is not completed after selecting a file from Open File Panel in Unity


string path;
AudioSource audio = GetComponent<AudioSource>();

path = EditorUtility.OpenFilePanel("Audio Files", "", "wav");
if (path != null)
{
    using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip("file:///" + path, AudioType.WAV))
        if (www.result == UnityWebRequest.Result.ConnectionError)
    {
        Debug.LogError(www.error);
    }
    else
        {
        //Debug.Log(www.url);
        audio.clip = DownloadHandlerAudioClip.GetContent(www);
        audio.Play();
            yield return www.SendWebRequest();
        }
}

after executing this block of code, on Play mode, A file picker runs successfully, however after selecting an audio file, the console throws the InvalidOperationException: Cannot get content from an unfinished UnityWebRequest object which caused by this line

audio.clip = DownloadHandlerAudioClip.GetContent(www);

my assumption is that I somehow missing a step in between getting the audio file path from the file picker and stream the actual audio clip using the path.

Debug.Log(www.url) will successfully print the file URI scheme.


Solution

  • In general watch out with your using .. you should wrap it in { } for readability and for preventing unexpected behavior

    Then for some reason you do

    yield return www.SendWebRequest();
    

    after trying to access the results .... this line should be the first after the using line .. before trying to check whether the request was sent correctly and trying to access the download content

    using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip("file:///" + path, AudioType.WAV))
    {
        yield return www.SendWebRequest();
    
        if (www.result == UnityWebRequest.Result.ConnectionError)
        {
            Debug.LogError(www.error);
        }
        else
        {
            audio.clip = DownloadHandlerAudioClip.GetContent(www);
            audio.Play();           
        }
    }