Please save me from going crazy.
No matter how many times I google, I always end up with (usually deprecated) versions of the following code:
IEnumer
You can do that with async/await:
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
public static async Task GetRemoteTexture ( string url )
{
using( UnityWebRequest www = UnityWebRequestTexture.GetTexture( url ) )
{
//begin requenst:
var asyncOp = www.SendWebRequest();
//await until it's done:
while( asyncOp.isDone==false )
{
await Task.Delay( 1000/30 );//30 hertz
}
//read results:
if( www.isNetworkError || www.isHttpError )
{
//log error:
#if DEBUG
Debug.Log( $"{ www.error }, URL:{ www.url }" );
#endif
//nothing to return on error:
return null;
}
else
{
//return valid results:
return DownloadHandlerTexture.GetContent( www );
}
}
}
Usage example:
[SerializeField] string _imageUrl;
[SerializeField] Material _material;
Texture2D _texture;
async void Start ()
{
_texture = await GetRemoteTexture( _imageUrl );
_material.mainTexture = _texture;
}
void OnDestroy () => Dispose();
public void Dispose () => Object.Destroy( _texture );// memory released, leak otherwise