0

I need to download an image from a server and show in sprite. All example I can find recommended next code:

WWW www = new WWW(requestUrl);
yield return www;
onTextureLoaded(www.texture,id);

But I can't find the way how to handle exceptions in this case. Should I add Try catch? Or is there any way to check if the request was successful?

Alex Myers
  • 6,196
  • 7
  • 23
  • 39
passer
  • 123
  • 1
  • 2
  • 7

2 Answers2

0

Like JeanLuc you should check www.error. But you should avoid WWW class since it's obsolete: https://docs.unity3d.com/ScriptReference/WWW.html

you should use UnityWebRequest instead

https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.Get.html

In that link you also find an example on how to check error with UnityWebRequest

LiefLayer
  • 977
  • 1
  • 12
  • 29
0
System.Collections.IEnumerator GetRemoteTexture ( string url )
{
    using( var www = UnityEngine.Networking.UnityWebRequestTexture.GetTexture( url ) )
    {
        //begin request:
        var asyncOp = www.SendWebRequest();

        //await until it's done:
        var hz30 = new WaitForSecondsRealtime( 1f/30f );
        while( asyncOp.isDone==false )
        {
            yield return hz30;
        }

        //read results:
        if( www.isNetworkError || www.isHttpError )
        {
            //log error:
            #if DEBUG
            Debug.Log( $"{ www.error }, URL:{ www.url }" );
            #endif
        }
        else
        {
            //success:
            Texture2D texture = UnityEngine.Networking.DownloadHandlerTexture.GetContent( www );

            //> DO SOMETHING WITH THIS TEXTURE HERE <

        }
    }
}

PRO version: https://stackoverflow.com/a/53770838/2528943

Andrew Łukasik
  • 1,454
  • 12
  • 19