How do I load an image via a URL in Unity?
I recently worked on the development of a Unity plugin. Where it was necessary to load images from a URL on a web server. In the end, the solution is rather simple and has the advantage of being asynchronous (which has almost no impact on performance).
Here's the resulting code:
public async Task<Texture2D> DownloadImage(string url, Action<Texture2D> callback)
{
UnityWebRequest www = UnityWebRequestTexture.GetTexture(url);
www.SendWebRequest();
while (!www.isDone)
{
await Task.Yield();
}
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log(www.error);
return null;
}
else
{
Texture2D texture = ((DownloadHandlerTexture)www.downloadHandler).texture;
callback(texture);
return texture;
}
}
There you go! Hope it can help you.